代码之家  ›  专栏  ›  技术社区  ›  Onorio Catenacci

如何在C#[duplicate]中获得从一条路径到另一条路径的相对路径

  •  27
  • Onorio Catenacci  · 技术社区  · 15 年前

    我希望有一个内置的.NET方法来实现这一点,但我没有找到它。

    我知道有两条路径在同一个根驱动器上,我希望能够获得从一条到另一条的相对路径。

    string path1 = @"c:\dir1\dir2\";
    string path2 = @"c:\dir1\dir3\file1.txt";
    string relPath = MysteryFunctionThatShouldExist(path1, path2); 
    // relPath == "..\dir3\file1.txt"
    

    这个功能存在吗?如果不是,那么最好的实施方式是什么?

    2 回复  |  直到 15 年前
        1
  •  62
  •   Marc Gravell    15 年前

    Uri 作品:

    Uri path1 = new Uri(@"c:\dir1\dir2\");
    Uri path2 = new Uri(@"c:\dir1\dir3\file1.txt");
    Uri diff = path1.MakeRelativeUri(path2);
    string relPath = diff.OriginalString;
    
        2
  •  14
  •   Leviculus    14 年前

    您还可以导入 PathRelativePathTo 函数并调用它。

    例如。:

    using System.Runtime.InteropServices;
    
    public static class Util
    {
      [DllImport( "shlwapi.dll", EntryPoint = "PathRelativePathTo" )]
      protected static extern bool PathRelativePathTo( StringBuilder lpszDst,
          string from, UInt32 attrFrom,
          string to, UInt32 attrTo );
    
      public static string GetRelativePath( string from, string to )
      {
        StringBuilder builder = new StringBuilder( 1024 );
        bool result = PathRelativePathTo( builder, from, 0, to, 0 );
        return builder.ToString();
      }
    }