开发者

Getting relative virtual path from physical path

开发者 https://www.devze.com 2023-03-07 17:09 出处:网络
How can I get the relative virtual path from the physical path in asp.net? The reverse method开发者_C百科 is like below:

How can I get the relative virtual path from the physical path in asp.net? The reverse method开发者_C百科 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);


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消