2011-05-21 117 views
36

如何从asp.net物理路径获取相对虚拟路径? 相反的方法是象下面这样:从物理路径获取相对虚拟路径

Server.MapPath("Virtual Path Here"); 

但什么是方法上的反向?

+8

考虑到IIS中的多个虚拟目录可能映射到相同的物理目录,即使在单个应用程序中也是如此。那么如何回答这个问题呢? – 2011-05-21 13:09:05

回答

32

也许this question是你在找什么。 在那里,他们建议:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty); 
22
public static string MapPathReverse(string fullServerPath) 
    {    
     return @"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath,String.Empty); 
    } 
+0

这适用,但在我的情况下,由于某种原因PhysicalApplicationPath是小写的,但我的fullServerPath中的路径即使从文件系统读取也不是。由于Windows没有区分大小写的路径,所以将其全部转换为小写可能没有问题 – 2017-01-12 08:04:24

8

你也可以做这样的事情:

string relativePath = absolutePath.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/"); 

的好处是,你不需要HttpContext.Current.Request

+0

这实际上是一个更好的答案,因为您不需要请求对象。 – 2017-08-21 10:57:08

9
Request.ServerVariables["APPL_PHYSICAL_PATH"] 

很好,但并不总是如此。只有存在HTTP请求时才可用。

在另一方面通话

HostingEnvironment.ApplicationPhysicalPath 

总是可用。