標籤:style blog http io ar color os sp for
引言
在項目中常需要將絕對路徑,轉換為相對路徑,來增加程式相關配置的的靈活性(不用因為整體挪個位置就導致我們的程式不能正常工作)
解決問題方法
自己寫代碼解決:
private string RelativePath(string absolutePath, string relativeTo) { string[] absoluteDirectories = absolutePath.Split(‘\\‘); string[] relativeDirectories = relativeTo.Split(‘\\‘); //Get the shortest of the two paths int length = absoluteDirectories.Length < relativeDirectories.Length ? absoluteDirectories.Length : relativeDirectories.Length; //Use to determine where in the loop we exited int lastCommonRoot = -1; int index; //Find common root for (index = 0; index < length; index++) if (absoluteDirectories[index] == relativeDirectories[index]) lastCommonRoot = index; else break; //If we didn‘t find a common prefix then throw if (lastCommonRoot == -1) throw new ArgumentException("Paths do not have a common base"); //Build up the relative path StringBuilder relativePath = new StringBuilder(); //Add on the .. for (index = lastCommonRoot + 1; index < absoluteDirectories.Length; index++) if (absoluteDirectories[index].Length > 0) relativePath.Append("..\\"); //Add on the folders for (index = lastCommonRoot + 1; index < relativeDirectories.Length - 1; index++) relativePath.Append(relativeDirectories[index] + "\\"); relativePath.Append(relativeDirectories[relativeDirectories.Length - 1]); return relativePath.ToString(); }
通過C#中URI類來解決:
System.Uri uri1 = new Uri(@"C:\filename.txt");System.Uri uri2 = new Uri(@"C:\mydirectory\anotherdirectory\"); Uri relativeUri = uri2.MakeRelativeUri(uri1); Console.WriteLine(relativeUri.ToString());
參考文獻
http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri(v=vs.110).aspx
相對路徑
C# 將絕對路徑轉換為相對路徑