如何在ASP.NET中从物理路径获取相对虚拟路径?反向方法如下:
Server.MapPath("Virtual Path Here");
但是上面方法的反方法是什么?
也许这个问题是你正在寻找的。 他们建议:
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"]
是可以的,但并非总是如此。它只在有HTTP请求时才可用。
另一方面,调用
HostingEnvironment.ApplicationPhysicalPath
始终可用。
您还可以像这样做:
string relativePath = absolutePath.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
优点是您不需要HttpContext.Current.Request
。