43

How can I get the relative virtual path from the physical path in asp.net? The reverse method is like below:

Server.MapPath("Virtual Path Here");

But what is the reverse of the upper method?

jdphenix
  • 15,022
  • 3
  • 41
  • 74
SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • 9
    Consider that multiple virtual directories in IIS may map to the same physical directory, even within a single application. How then can this question be answered? – Damien_The_Unbeliever May 21 '11 at 13:09

4 Answers4

34

Maybe this question is what you're looking for. There they suggest:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
Community
  • 1
  • 1
Felix Martinez
  • 3,928
  • 3
  • 31
  • 32
26
    public static string MapPathReverse(string fullServerPath)
    {            
        return @"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath,String.Empty);
    }
Iman
  • 17,932
  • 6
  • 80
  • 90
  • This works but in my case PhysicalApplicationPath was in lower case for some reason but the path in my fullServerPath wasn't even though it was read from the file system. Since Windows doesn't have case insensitive paths it's probably okay to convert it all to lower case – Matthew Lock Jan 12 '17 at 08:04
14
Request.ServerVariables["APPL_PHYSICAL_PATH"]

is fine, but not always. It is available only if there's a HTTP request.

On the other hand the call

HostingEnvironment.ApplicationPhysicalPath

is always available.

Alexander Christov
  • 9,625
  • 7
  • 43
  • 58
10

You could also do something like this:

string relativePath = absolutePath.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");

The advantage is, that you don't need HttpContext.Current.Request.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Pierre Chavaroche
  • 1,253
  • 16
  • 12