源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C#计算两个文件的相对目录算法的实例代码

  • 时间:2020-01-26 05:39 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#计算两个文件的相对目录算法的实例代码
楼主大菜鸟一只,第一次写技术博客,如果有概念错误或代码不规范的地方,还请各位多多批评指正。话不多说,来看题: 前一阵子开发了一个用户控件,里面调用了很多css,js等资源文件,而引用控件的页面所在目录是不同的。问题出来了:如果目录不同,那么控件里引用css,js资源文件的路径也会相应变化。现在已知两个文件相对于网站根目录的路径,如何计算相对路径呢?请看代码:
[u]复制代码[/u] 代码如下:
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的相对路径,第四步把第二步和第三步的结果相加就是我们要的答案了。 调用部分:
[u]复制代码[/u] 代码如下:
string path1 = "/Manage/Permissions/RoleManage.aspx"; string path2 = "/Manage/plugin/jquery-easyui/jquery.easyui.min.js"; string result = GetRelativePath(path1, path2);
得到结果:../plugin/jquery-easyui/jquery.easyui.min.js
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部