c#如何獲取相對(duì)路徑

c#
小億
211
2024-08-11 13:01:36
欄目: 編程語言

要獲取相對(duì)路徑,可以使用以下方法:

  1. 使用 System.IO.Path.GetRelativePath 方法來獲取相對(duì)路徑。

    string relativePath = System.IO.Path.GetRelativePath(basePath, targetPath);
    
  2. 使用 System.IO.Path.GetDirectoryName 方法獲取目標(biāo)路徑的父目錄,然后使用 System.IO.Path.GetRelativePath 方法獲取相對(duì)路徑。

    string basePath = @"C:\BaseFolder";
    string targetPath = @"C:\BaseFolder\SubFolder\file.txt";
    
    string relativePath = System.IO.Path.GetRelativePath(System.IO.Path.GetDirectoryName(basePath), targetPath);
    
  3. 使用自定義方法來計(jì)算相對(duì)路徑。

    public static string GetRelativePath(string fromPath, string toPath)
    {
        Uri fromUri = new Uri(fromPath);
        Uri toUri = new Uri(toPath);
    
        Uri relativeUri = fromUri.MakeRelativeUri(toUri);
    
        return Uri.UnescapeDataString(relativeUri.ToString());
    }
    
    string basePath = @"C:\BaseFolder";
    string targetPath = @"C:\BaseFolder\SubFolder\file.txt";
    
    string relativePath = GetRelativePath(basePath, targetPath);
    

0