Thursday, October 7, 2010

How to get virtual path from physical path in ASP.NET?

Let's do the opposite of what Server.MapPath does. Is not so hard. Just a c# method and 4 lines of code.


We all know that in ASP.NET the method Server.MapPath give us the physical path given a virtual path, right? Now, you might need to do just the opposite… why not? I googled a lot on this, but found no suitable and/or pretty solution so I just coded this method in c# (yes, I love C#). It works fine for me, hope you can find it useful too.

public string GetVirtualPath(string physicalPath)
{
string rootpath = Server.MapPath("~/");
physicalPath = physicalPath.Replace(rootpath,
"");
physicalPath = physicalPath.Replace(
"\\", "/");
return "~/" + physicalPath;
}

Converting this C# method to VB.NET is quite easy, so no need for that.

No comments:

Post a Comment