从物理路径获取相对虚拟路径

Sil*_*ght 39 c# asp.net path

如何从asp.net中的物理路径获取相对虚拟路径?反向方法如下:

Server.MapPath("Virtual Path Here");
Run Code Online (Sandbox Code Playgroud)

但是上层方法的反转是什么?

fel*_*xmm 32

也许这个问题就是你要找的.在那里他们建议:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
Run Code Online (Sandbox Code Playgroud)


Ima*_*idi 25

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


Ale*_*tov 12

Request.ServerVariables["APPL_PHYSICAL_PATH"]
Run Code Online (Sandbox Code Playgroud)

很好,但并非总是如此.只有在有HTTP请求时才可用.

另一方面是电话

HostingEnvironment.ApplicationPhysicalPath
Run Code Online (Sandbox Code Playgroud)

始终可用.


Pie*_*che 9

你也可以这样做:

string relativePath = absolutePath.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
Run Code Online (Sandbox Code Playgroud)

优点是,你不需要HttpContext.Current.Request.