SilverLight
SilverLight

Reputation: 20468

Getting relative virtual path from physical path

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?

Upvotes: 44

Views: 90956

Answers (4)

Alexander Christov
Alexander Christov

Reputation: 10045

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.

Upvotes: 14

Pierre Chavaroche
Pierre Chavaroche

Reputation: 1293

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.

Upvotes: 11

Iman
Iman

Reputation: 18876

    public static string MapPathReverse(string fullServerPath)
    {            
        return @"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath,String.Empty);
    }

Upvotes: 27

Felix Martinez
Felix Martinez

Reputation: 3978

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

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

Upvotes: 34

Related Questions