Absolute path back to web-relative path


If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastest way to convert that absolute path back into a relative web path?

3/20/2018 2:51:34 PM

Accepted Answer

Perhaps this might work:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);

I'm using c# but could be adapted to vb.

3/20/2018 2:18:12 PM

Wouldn't it be nice to have Server.RelativePath(path)?

well, you just need to extend it ;-)

public static class ExtensionMethods
    public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
        return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/");

With this you can simply call

Server.RelativePath(path, Request);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow