有需求或技術問題可以隨時跟我連絡 (MSN上線時)

2009年3月18日 星期三

絕對路徑 轉 相對路徑

有時候,在程式處裡的過程中,尤其是一些設定檔案(*.INI,*.xml,*.config...),你想要儲存的路徑(Path)是相對於某的檔案(通常至執行檔Execution File),你需要作路徑轉換,以方便整個檔案資料夾換位置時,無須在設定路徑,這時候你會需要以相對路徑的方式來儲存比較方便.
舉例來說:
檔案:D:\Visual Studio 2005\Projects\路徑轉換\路徑轉換\Form1.cs
相對於D:\Visual Studio 2005\Projects\路徑轉換\路徑轉換\bin\Debug 資料夾
使用..\..\Form1.cs 的方式來表示
以下是轉換函數,提供需要的人參考....
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();
}