c# - physical - server.mappath mvc

Getting relative virtual path from physical path (3)

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?

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

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

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.


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

On the other hand the call


is always available.