How to get relative path from absolute path

前端 未结 23 2071
既然无缘
既然无缘 2020-11-22 11:52

There\'s a part in my apps that displays the file path loaded by the user through OpenFileDialog. It\'s taking up too much space to display the whole path, but I don\'t want

23条回答
  •  误落风尘
    2020-11-22 12:30

    I'm using this:

    public static class StringExtensions
    {
      /// 
      /// Creates a relative path from one file or folder to another.
      /// 
      /// Absolute path.
      /// Directory that defines the start of the relative path. 
      /// The relative path from the start directory to the end path.
      public static string MakeRelativePath(this string absPath, string relTo)
      {
          string[] absParts = absPath.Split(Path.DirectorySeparatorChar);
          string[] relParts = relTo.Split(Path.DirectorySeparatorChar);
    
          // Get the shortest of the two paths
          int len = absParts.Length < relParts.Length
              ? absParts.Length : relParts.Length;
    
          // Use to determine where in the loop we exited
          int lastCommonRoot = -1;
          int index;
    
          // Find common root
          for (index = 0; index < len; index++)
          {
              if (absParts[index].Equals(relParts[index], StringComparison.OrdinalIgnoreCase))
                  lastCommonRoot = index;
              else 
                break;
          }
    
          // If we didn't find a common prefix then throw
          if (lastCommonRoot == -1)
              throw new ArgumentException("The path of the two files doesn't have any common base.");
    
          // Build up the relative path
          var relativePath = new StringBuilder();
    
          // Add on the ..
          for (index = lastCommonRoot + 1; index < relParts.Length; index++)
          {
            relativePath.Append("..");
            relativePath.Append(Path.DirectorySeparatorChar);
          }
    
          // Add on the folders
          for (index = lastCommonRoot + 1; index < absParts.Length - 1; index++)
          {
            relativePath.Append(absParts[index]);
            relativePath.Append(Path.DirectorySeparatorChar);
          }
          relativePath.Append(absParts[absParts.Length - 1]);
    
          return relativePath.ToString();
      }
    }
    

提交回复
热议问题