Peter Meyer
Peter Meyer

Reputation: 26051

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?

Upvotes: 27

Views: 7576

Answers (4)

Ehsan Abidi
Ehsan Abidi

Reputation: 959

VirtualPathUtility class at System.Web as Microsoft Help said: provides utility methods for common virtual path operations. But as far as I can see, it doesn`t have a method for the purpose of this question.
The following code, which expected to work, but returns an exception:

VirtualPathUtility.ToAppRelative(@"D:\Abidi\Passports\PdfImage4.jpg") // exception

Upvotes: -1

vGHazard
vGHazard

Reputation: 117

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

Upvotes: -2

Shazwazza
Shazwazza

Reputation: 811

Isn't this what UrlHelper.Content method does? http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content.aspx

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827366

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;
}

Upvotes: 29

Related Questions