【问题标题】:How do I get a relative path from one path to another in C# [duplicate]如何在 C# 中获取从一条路径到另一条路径的相对路径 [重复]
【发布时间】:2009-11-19 21:37:58
【问题描述】:

我希望有一个内置的 .NET 方法来执行此操作,但我没有找到它。

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

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

这个函数存在吗?如果不是,最好的实现方式是什么?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    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;
    

    【讨论】:

    • Uri 确实有效,但会切换到正斜杠,这很容易修复。谢谢!
    • 不仅要注意正斜杠!最好添加 UnescapeDataString。 string relPath = Uri.UnescapeDataString(diff.OriginalString);
    • 从 .Net 5 / .Net Core 2 开始,还有 MakeRelative;这似乎与MakeRelativeUri(...).OriginalString 相同。 docs.microsoft.com/en-us/dotnet/api/…
    【解决方案2】:

    您也可以导入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();
      }
    }
    

    【讨论】:

    • 对我有用,但我必须删除“受保护”,否则(使用 VS2012,.NET3.5)我收到错误 CS1057:“PathRelativePathTo(System.Text.StringBuilder, string, uint , string, uint)': 静态类不能包含受保护的成员"
    • 为这样的简单案例导入 win32 API 似乎有些过头了,尽管很高兴知道这是可能的。
    • @FacelessPanda 这并不过分——该库几乎可以肯定已加载,因此使用它的开销为零。
    • @FacelessPanda 看到 .NET Framework 源代码你会非常失望! :) System.Windows.Forms 特别是:referencesource.microsoft.com/#System.Windows.Forms,namespaces
    • @AdamPlocher 你给出的例子并不令人惊讶,因为 Windows 窗体只不过是一个 WinAPI 包装器。
    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 2011-12-26
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多