How to get relative path from absolute path

前端 未结 23 2200
既然无缘
既然无缘 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:49

    I have used this in the past.

    /// 
    /// Creates a relative path from one file
    /// or folder to another.
    /// 
    /// 
    /// Contains the directory that defines the
    /// start of the relative path.
    /// 
    /// 
    /// Contains the path that defines the
    /// endpoint of the relative path.
    /// 
    /// 
    /// The relative path from the start
    /// directory to the end path.
    /// 
    /// 
    public static string MakeRelative(string fromDirectory, string toPath)
    {
      if (fromDirectory == null)
        throw new ArgumentNullException("fromDirectory");
    
      if (toPath == null)
        throw new ArgumentNullException("toPath");
    
      bool isRooted = (Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath));
    
      if (isRooted)
      {
        bool isDifferentRoot = (string.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true) != 0);
    
        if (isDifferentRoot)
          return toPath;
      }
    
      List relativePath = new List();
      string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);
    
      string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);
    
      int length = Math.Min(fromDirectories.Length, toDirectories.Length);
    
      int lastCommonRoot = -1;
    
      // find common root
      for (int x = 0; x < length; x++)
      {
        if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)
          break;
    
        lastCommonRoot = x;
      }
    
      if (lastCommonRoot == -1)
        return toPath;
    
      // add relative folders in from path
      for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
      {
        if (fromDirectories[x].Length > 0)
          relativePath.Add("..");
      }
    
      // add to folders to path
      for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
      {
        relativePath.Add(toDirectories[x]);
      }
    
      // create relative path
      string[] relativeParts = new string[relativePath.Count];
      relativePath.CopyTo(relativeParts, 0);
    
      string newPath = string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);
    
      return newPath;
    }
    

提交回复
热议问题