【问题标题】:Getting relative virtual path from physical path从物理路径获取相对虚拟路径
【发布时间】:2011-08-30 04:48:36
【问题描述】:

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

Server.MapPath("Virtual Path Here");

但是上面方法的反面是什么?

【问题讨论】:

  • 请考虑 IIS 中的多个虚拟目录可能映射到同一个物理目录,即使在单个应用程序中也是如此。那么如何回答这个问题呢?

标签: c# asp.net path


【解决方案1】:

也许this question 就是您要找的东西。 他们建议:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);

【讨论】:

    【解决方案2】:
        public static string MapPathReverse(string fullServerPath)
        {            
            return @"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath,String.Empty);
        }
    

    【讨论】:

    • 这可行,但在我的情况下,PhysicalApplicationPath 由于某种原因是小写的,但我的 fullServerPath 中的路径不是即使它是从文件系统中读取的。由于 Windows 没有不区分大小写的路径,因此将其全部转换为小写可能没问题
    【解决方案3】:
    Request.ServerVariables["APPL_PHYSICAL_PATH"]
    

    很好,但并非总是如此。它仅在有 HTTP 请求时可用。

    另一方面是调用

    HostingEnvironment.ApplicationPhysicalPath
    

    始终可用。

    【讨论】:

      【解决方案4】:

      你也可以这样做:

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

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

      【讨论】:

      • 这实际上是一个更好的答案,因为您不需要请求对象。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2011-06-29
      相关资源
      最近更新 更多