Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to perform the reverse of Server.MapPath in an ASP.Net Application

I am building an MVC application in which I am reading a list of files from the file system and I want to pass the relative URL to that file to the view, preferably prefixed with "~/" so that whatever view is selected cab render the URL appropriately.

To do this, I need to enumerate the files in the file system and convert their physical paths back to relative URLs. There are a few algorithms I've experimented with, but I am concerned about efficiency and minimal string operations. Also, I believe there's nothing in the .Net Framework that can perform this operation, but is there something in the latest MVC release that can?

like image 952
Peter Meyer Avatar asked Dec 28 '08 03:12

Peter Meyer


People also ask

What is server MapPath in asp net c#?

Because the MapPath method maps a path regardless of whether the specified directories currently exist, you can use the MapPath method to map a path to a physical directory structure, and then pass that path to a component that creates the specified directory or file on the server.

What value is return by server MapPath method?

If path is null , the MapPath method returns the full physical path of the directory that contains the current request for the path. The relative path does not need to specify an existing file or folder for this method to return a value.

What is server MapPath in MVC?

Many times we need to know the full path of remote server where we are hosting or the exact location of file but if we don't how we can't. Actually we have MapPath method which maps the specified relative or virtual path to the corresponding physical directory on the web server.


1 Answers

At the moment I don't know any built-in method to do it, but it's not difficult, I do it like this:

  • We need to get the Application root, and replace it in our new path with ~
  • We need to convert the backslashes to slashes

public string ReverseMapPath(string path) {     string appPath = HttpContext.Current.Server.MapPath("~");     string res = string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/"));     return res; } 
like image 166
Christian C. Salvadó Avatar answered Sep 22 '22 00:09

Christian C. Salvadó