前一阵子开发了一个用户控件,里面调用了很多css,js等资源文件,而引用控件的页面所在目录是不同的。问题出来了:如果目录不同,那么控件里引用css,js资源文件的路径也会相应变化。现在已知两个文件相对于网站根目录的路径,如何计算相对路径呢?请看代码:
public string GetRelativePath(string path1, string path2)
{
            string[] path1Array = path1.Split('/');
            string[] path2Array = path2.Split('/');
            //
            int s = path1Array.Length >= path2Array.Length ? path2Array.Length : path1Array.Length;
            //两个目录最底层的共用目录索引
            int closestRootIndex = -1;
            for (int i = 0; i < s; i++)
            {
                if (path1Array[i] == path2Array[i])
                {
                    closestRootIndex = i;
                }
                else
                {
                    break;
                }
            }
            //由path1计算 ‘../'部分
            string path1Depth = "";
            for (int i = 0; i < path1Array.Length; i++)
            {
                if (i > closestRootIndex + 1)
                {
                    path1Depth += "../";
                }
            }
            //由path2计算 ‘../'后面的目录
            string path2Depth = "";
            for (int i = closestRootIndex + 1; i < path2Array.Length; i++)
            {
                path2Depth += "/" + path2Array[i];
            }
            path2Depth = path2Depth.Substring(1);
            return path1Depth + path2Depth;
}
 
我的算法,第一步算出两个目录的最底层父目录,第二步算出目录1需要向上级目录返回次数(../个数),第三步算出最底层父目录到目录2的相对路径,第四步把第二步和第三步的结果相加就是我们要的答案了。