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?
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;
}
Isn't this what UrlHelper.Content method does? http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content.aspx
I did some digging, trying to get the UrlHelper class to work outside of a controller, then I remembered a old trick to do the same thing within an aspx page:
string ResolveUrl(string pathWithTilde)
Hope this helps!
See:
https://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl(v=vs.110).aspx