How to get relative path from absolute path

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

    .NET Core 2.0 has Path.GetRelativePath, else, use this.

    /// 
    /// 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 or toPath if the paths are not related.
    /// 
    /// 
    /// 
    public static String MakeRelativePath(String fromPath, String toPath)
    {
        if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
        if (String.IsNullOrEmpty(toPath))   throw new ArgumentNullException("toPath");
    
        Uri fromUri = new Uri(fromPath);
        Uri toUri = new Uri(toPath);
    
        if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.
    
        Uri relativeUri = fromUri.MakeRelativeUri(toUri);
        String relativePath = Uri.UnescapeDataString(relativeUri.ToString());
    
        if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
        {
            relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
        }
    
        return relativePath;
    }
    

提交回复
热议问题