C#计算两个文件的相对目录算法

C#计算两个文件的相对目录算法

楼主大菜鸟一只,第一次写技术博客,如果有概念错误或代码不规范的地方,还请各位多多批评指正。话不多说,来看题:

  前一阵子开发了一个用户控件,里面调用了很多css,js等资源文件,而引用控件的页面所在目录是不同的。问题出来了:如果目录不同,那么控件里引用css,js资源文件的路径也会相应变化。现在已知两个文件相对于网站根目录的路径,如何计算相对路径呢?请看代码:

复制代码
 1 public string GetRelativePath(string path1, string path2)
 2 {
 3             string[] path1Array = path1.Split('/');
 4             string[] path2Array = path2.Split('/');
 5             //
 6             int s = path1Array.Length >= path2Array.Length ? path2Array.Length : path1Array.Length;
 7             //两个目录最底层的共用目录索引
 8             int closestRootIndex = -1;
 9             for (int i = 0; i < s; i++)
10             {
11                 if (path1Array[i] == path2Array[i])
12                 {
13                     closestRootIndex = i;
14                 }
15                 else
16                 {
17                     break;
18                 }
19             }
20             //由path1计算 ‘../’部分
21             string path1Depth = "";
22             for (int i = 0; i < path1Array.Length; i++)
23             {
24                 if (i > closestRootIndex + 1)
25                 {
26                     path1Depth += "../";
27                 }
28             }
29             //由path2计算 ‘../’后面的目录
30             string path2Depth = "";
31             for (int i = closestRootIndex + 1; i < path2Array.Length; i++)
32             {
33                 path2Depth += "/" + path2Array[i];
34             }
35             path2Depth = path2Depth.Substring(1);
36 
37             return path1Depth + path2Depth;
38 }
复制代码

我的算法,第一步算出两个目录的最底层父目录,第二步算出目录1需要向上级目录返回次数(../个数),第三步算出最底层父目录到目录2的相对路径,第四步把第二步和第三步的结果相加就是我们要的答案了。

调用部分:

1        string path1 = "/Manage/Permissions/RoleManage.aspx";
2             string path2 = "/Manage/plugin/jquery-easyui/jquery.easyui.min.js";
3             string result = GetRelativePath(path1, path2);

得到结果:../plugin/jquery-easyui/jquery.easyui.min.js

原文地址:https://www.cnblogs.com/Leo_wl/p/3305828.html