通过以下函数方法可以获得pathB相对于pathA的相对路径
//关于获取相对路径的计算
private static string GetRelativePath(string pathA, string pathB) {
string[] pathAArray = pathA.Split('\\');
string[] pathBArray = pathB.Split('\\');
//返回2者之间的最小长度
int s = pathAArray.Length >= pathBArray.Length ? pathBArray.Length : pathAArray.Length;
//两个目录最底层的共用目录的索引
int closestRootIndex = -1;
for (int i = 0; i < s; i++) {
if (pathAArray[i] == pathBArray[i]) {
closestRootIndex = i;
}
else {
break;
}
}
//由pathA计算 ‘../’部分
string pathADepth = "";
for (int i = 0; i < pathAArray.Length; i++) {
if (i > closestRootIndex + 1) {
pathADepth += "../";
}
}
//由pathB计算‘../’后面的目录
string pathBdepth = "";
for (int i = closestRootIndex + 1; i < pathBArray.Length; i++) {
pathBdepth += "/" + pathBArray[i];
}
pathBdepth = pathBdepth.Substring(1);//去掉重复的斜杠 “ / ”
return pathADepth + pathBdepth;//pathB相对于pathA的相对路径
}