【发布时间】:2011-08-30 04:48:36
【问题描述】:
如何从asp.net中的物理路径获取相对虚拟路径? 反向方法如下:
Server.MapPath("Virtual Path Here");
但是上面方法的反面是什么?
【问题讨论】:
-
请考虑 IIS 中的多个虚拟目录可能映射到同一个物理目录,即使在单个应用程序中也是如此。那么如何回答这个问题呢?
如何从asp.net中的物理路径获取相对虚拟路径? 反向方法如下:
Server.MapPath("Virtual Path Here");
但是上面方法的反面是什么?
【问题讨论】:
也许this question 就是您要找的东西。 他们建议:
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。
【讨论】: