views:

282

answers:

1

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?

+1  A: 

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;
}
CMS
I have something similar right now. What I don't like is calling this in a loop for a bunch of enumerated files and all the calls to MapPath, String.Replace a String.Format. In terms of optimization, passing in the appPath can eliminate the calls to MapPath. Perhaps there's nothing better?!
Peter Meyer
If performance is your concern, you could have a service or something monitor the directories out of band, translate the paths to relative urls, store them somewhere, and use that data store to get the url to pass to the view. May not be worth the trouble depending on how many files you have.
JasonS