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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

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

Method 2

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

Method 3

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.

Method 4

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x