【问题标题】:Getting the relative path from the full path从完整路径获取相对路径
【发布时间】:2011-12-11 17:00:21
【问题描述】:

我必须从完整路径中获取不包括相对路径的路径, 说

相对路径是,C:\User\Documents\

完整路径,C:\User\Documents\Test\Folder2\test.pdf

我只想获取相对路径之后的路径,即 \Test\Folder2\test.pdf

我怎样才能做到这一点。

我使用 C# 作为编程语言

【问题讨论】:

标签: c# path relative-path


【解决方案1】:

你不是在谈论相对,所以我称之为部分路径。 如果您可以确定部分路径是完整路径的一部分,则它是一个简单的字符串操作:

string fullPath = @"C:\User\Documents\Test\Folder2\test.pdf";
string partialPath = @"C:\User\Documents\";
string resultingPath = fullPath.Substring(partialPath.Length);

但这需要一些错误检查 - 当 fullPath 或 partialPath 为 null 或两个路径具有相同长度时,它将失败。

【讨论】:

    【解决方案2】:

    嗯,但是如果情况不同呢?或者其中一个路径对其文件夹使用短名称?更完整的解决方案是......

    public static string GetRelativePath(string fullPath, string containingFolder,
        bool mustBeInContainingFolder = false)
    {
        var file = new Uri(fullPath);
        if (containingFolder[containingFolder.Length - 1] != Path.DirectorySeparatorChar)
            containingFolder += Path.DirectorySeparatorChar;
        var folder = new Uri(containingFolder); // Must end in a slash to indicate folder
        var relativePath =
            Uri.UnescapeDataString(
                folder.MakeRelativeUri(file)
                    .ToString()
                    .Replace('/', Path.DirectorySeparatorChar)
                );
        if (mustBeInContainingFolder && relativePath.IndexOf("..") == 0)
            return null;
        return relativePath;
    }
    

    【讨论】:

      【解决方案3】:

      要扩展 Jan 的答案,您可以在 string 类(或 Path 类,如果需要)上创建扩展方法,例如:

      namespace ExtensionMethods
      {
          public static class MyExtensions
          {
              public static string GetPartialPath(this string fullPath, string partialPath)
              {
                  return fullPath.Substring(partialPath.Length)
              }
          }   
      }
      

      然后使用:

      using ExtensionMethods;
      string resultingPath = string.GetPartialPath(partialPath);
      

      我还没有测试过这个扩展方法是否有效,但是should do

      【讨论】:

        猜你喜欢
        • 2019-08-10
        • 1970-01-01
        • 2014-10-29
        • 2018-08-13
        • 2017-03-16
        • 1970-01-01
        • 2022-06-10
        • 2014-12-08
        相关资源
        最近更新 更多