1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
string CalculateRelativePath(string pathA, string pathB) { if (string.IsNullOrEmpty(pathA) || string.IsNullOrEmpty(pathB)) throw new Exception("路径不能为空额"); if (pathA.Equals(pathB)) return "";
char[] temp = new char[] { '/', '\\' }; string[] tempA = pathA.Split(temp); string[] tempB = pathB.Split(temp);
int maxLength = (tempB.Length > tempA.Length) ? tempB.Length : tempA.Length; int sameFolderCount = 0; for (int i = 0; i < maxLength; i++) { if (tempA[i] == tempB[i]) ++sameFolderCount; else break; } int diffFolderCount = maxLength - sameFolderCount;
System.Text.StringBuilder builder = new System.Text.StringBuilder(); while (diffFolderCount-- > 0) builder.Append("../");
for (int i = sameFolderCount; i < tempB.Length; i++) { builder.Append(tempB[i]); builder.Append("/"); }
return builder.ToString().TrimEnd('/'); }
|