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
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.