程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#相對路徑轉絕對路徑,絕對路徑轉相對路徑,

C#相對路徑轉絕對路徑,絕對路徑轉相對路徑,

編輯:C#入門知識

C#相對路徑轉絕對路徑,絕對路徑轉相對路徑,


 

1.絕對路徑轉相對路徑

 

絕對轉相對似乎C#沒有提供實現,需要自己寫,這裡摘選了一位博友的實現方法:

string RelativePath(string absolutePath, string relativeTo) { //from - www.cnphp6.com 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(); } RelativePath

 

調用:

static void Main(string[] args)
{
    var path = RelativePath(@"D:\MyProj\Release", @"D:\MyProj\Log\MyFile.txt");

    Console.WriteLine(path);//print ..\Log\MyFile.txt
    Console.Read();
}

 

 

2.相對路徑轉絕對路徑

 

可以直接用.Net自己的Path.GetFullPath轉換

static void Main(string[] args)
{
    var relativePath = @"..\..\Release";
    Console.WriteLine(Path.GetFullPath(relativePath));
    Console.Read();
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved