如何在C#中获取从一个路径到另一个路径的相对路径

时间:2009-11-19 21:37:58

标签: c# .net

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

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

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

这个功能存在吗?如果不是最好的方法来实现它?

2 个答案:

答案 0 :(得分:54)

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;

答案 1 :(得分:11)

您也可以导入PathRelativePathTo功能并调用它。

e.g:

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();
  }
}