【原創源碼】(05):C#-計算絕對路徑。
歡迎大家發表意見(漏洞,效能等)。在部落格園社區以外轉載,請註明作者和出處。謝謝!
/**//// <summary>
/// 計算絕對路徑
/// </summary>
/// <param name="absoluteDir">絕對目錄</param>
/// <param name="relativeFile">相對檔案</param>
/// <returns></returns>
/// <example>
/// @"D:\Windows\regedit.exe" = GetAbsolutePath(@"D:\Windows\Web\Wallpaper\", @"..\..\regedit.exe" );
/// </example>
public static string GetAbsolutePath(string absoluteDir, string relativeFile)
{
bool isNotOver = true;
int intStart = 0;
while (isNotOver)
{
if (relativeFile.StartsWith(@"..\"))
{
relativeFile = relativeFile.Remove(0, 3);
intStart++;
}
else
{
isNotOver = false;
}
}
if (intStart > 0)
{
if (absoluteDir.EndsWith("\\"))
{
absoluteDir = absoluteDir.Remove(absoluteDir.Length - 1);
}
for (int i = 0; i < intStart; i++)
{
absoluteDir = absoluteDir.Remove(absoluteDir.LastIndexOf("\\"));
}
}
return Path.Combine(absoluteDir, relativeFile);
}
下面這個方法效率是樓上的1/50。。。
public static string GetAbsolutePath(string dir, string path)
{
string strDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(dir);
string strNew = Path.GetFullPath(path);
Directory.SetCurrentDirectory(strDir);
return strNew;
}