C# 在C语言中,如何获得从一条路径到另一条路径的相对路径#

C# 在C语言中,如何获得从一条路径到另一条路径的相对路径#,c#,.net,C#,.net,我希望有一个内置的.NET方法来实现这一点,但我没有找到它 我知道有两条路径在同一个根驱动器上,我希望能够获得从一条到另一条的相对路径 string path1 = @"c:\dir1\dir2\"; string path2 = @"c:\dir1\dir3\file1.txt"; string relPath = MysteryFunctionThatShouldExist(path1, path2); // relPath == "..\dir3\file1.txt" 这个功能存在吗?

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

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

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

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

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;

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

e、 g:


Uri确实可以工作,但会切换到正向斜杠,这很容易修复。谢谢不仅要小心向前砍!最好添加UnescapeDataString。string relPath=Uri.UnescapeDataString(diff.OriginalString);从.NET5/.NETCore2开始,还有
MakeRelative
;这似乎与
MakeRelativeUri(…).OriginalString
的作用相同。对我来说是可行的,但我必须删除“受保护的”,否则(使用VS2012,.NET3.5)我会得到错误CS1057:“PathRelativePathTo(System.Text.StringBuilder,string,uint,string,uint)”:静态类不能包含受保护的成员“为这样一个简单的情况导入win32 API似乎有些过分,尽管知道这是可能的很高兴。@FacelessPanda这并不是过分的-库几乎肯定是加载的,所以使用它没有任何开销。@FacelessPanda如果看到.NET Framework源代码,您会非常失望的!:)特别是System.Windows.Forms:@AdamPlocher您给出的示例并不令人惊讶,因为Windows窗体从来都不是WinAPI包装器。
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();
  }
}