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?
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.
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.
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.
At the moment I don't know any built-in method to do it, but it's not difficult, I do it like this:
~
public string ReverseMapPath(string path) { string appPath = HttpContext.Current.Server.MapPath("~"); string res = string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/")); return res; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With