How to get relative path from absolute path

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

    Way with Uri not worked on linux/macOS systems. Path '/var/www/root' can't be converted to Uri. More universal way - do all by hands.

    public static string MakeRelativePath(string fromPath, string toPath, string sep = "/")
    {
        var fromParts = fromPath.Split(new[] { '/', '\\'},
            StringSplitOptions.RemoveEmptyEntries);
        var toParts = toPath.Split(new[] { '/', '\\'},
            StringSplitOptions.RemoveEmptyEntries);
    
        var matchedParts = fromParts
            .Zip(toParts, (x, y) => string.Compare(x, y, true) == 0)
            .TakeWhile(x => x).Count();
    
        return string.Join("", Enumerable.Range(0, fromParts.Length - matchedParts)
            .Select(x => ".." + sep)) +
                string.Join(sep, toParts.Skip(matchedParts));
    }        
    

    PS: i use "/" as a default value of separator instead of Path.DirectorySeparatorChar, because result of this method used as uri in my app.

提交回复
热议问题