C#-計算相對路徑
/**//// <summary>
/// 計算相對路徑
/// 後者相對前者的路徑。
/// </summary>
/// <param name="mainDir">主目錄</param>
/// <param name="fullFilePath">檔案的絕對路徑</param>
/// <returns>fullFilePath相對於mainDir的路徑</returns>
/// <example>
/// @"..\..\regedit.exe" = GetRelativePath(@"D:\Windows\Web\Wallpaper\", @"D:\Windows\regedit.exe" );
/// </example>
public static string GetRelativePath(string mainDir, string fullFilePath)
{
if (!mainDir.EndsWith("\\"))
{
mainDir += "\\";
}
int intIndex = -1, intPos = mainDir.IndexOf('\\');
while (intPos >= 0)
{
intPos++;
if (string.Compare(mainDir, 0, fullFilePath, 0, intPos, true) != 0) break;
intIndex = intPos;
intPos = mainDir.IndexOf('\\', intPos);
}
if (intIndex >= 0)
{
fullFilePath = fullFilePath.Substring(intIndex);
intPos = mainDir.IndexOf("\\", intIndex);
while (intPos >= 0)
{
fullFilePath = "..\\" + fullFilePath;
intPos = mainDir.IndexOf("\\", intPos + 1);
}
}
return fullFilePath;
}