zoukankan      html  css  js  c++  java
  • MapPath的反函数(Reversing MapPath)

    首先需要说明的一点是,目前Google到的结果,前几个解决方案是错的,因为它没有考虑到应用的虚拟根目录不是/的情况.

    比如,如果应用的物理根目录是c:\website\piic\en,应用的虚拟路径为/en/,文件的路径为c:\websites\piic\en\images\aaa.jpg的话,按那几个解决方案,得到的结果将会是/images/aaa.jpg,而实际上应该是/en/images/aaa.jpg.

    并且,MapPath是可以这么用的: MapPath("~/aaa.jpg"), 上述解决方案也没有处理这个特殊的目录(~).

    下面附上我的解决方案:

    Code
            /// <summary>
            
    /// Reverse of MapPath
            
    /// </summary>
            
    /// <param name="path">File path in the disk</param>
            
    /// <returns>virtual path in current web application</returns>
            public static string PathMap(string path)
            {
                
    // example 1:
                
    // path: c:\websites\piic\en\images\aaa.jpg
                
    // application root: c:\website\piic\en
                
    // virtual root: /
                
    // result: /en/images/aaa.jpg

                
    // example 2:
                
    // path: c:\websites\piic\en\images\aaa.jpg
                
    // application root: c:\website\piic\en
                
    // virtual root: /en/
                
    // result: /en/images/aaa.jpg


                
    if (path.StartsWith("~/"))
                {
                    var virtualRoot 
    = HostingEnvironment.ApplicationVirtualPath;
                    path 
    = virtualRoot + path.Substring(2);
                }

                var approot 
    = HostingEnvironment.ApplicationPhysicalPath;

                
    return path.Replace(approot, string.Empty).Replace('\\''/');
            }

  • 相关阅读:
    阿里巴巴面试题集合
    mysql的面试试题
    taobao面试要点
    properties文件value换行处理方式
    nginx添加需要代理的域名 配置
    spark基本概念
    MySQL半同步Semi-sync原理介绍【图说】
    J_D 仓储所用mysql版本
    mysql数据库的物理文件结构
    判断浏览器
  • 原文地址:https://www.cnblogs.com/deerchao/p/1590284.html
Copyright © 2011-2022 走看看