Since .NET doesn't include an API to make relative paths, I've used Uri's MakeRelativeUri
method instead. This works, but I've encountered several cases in which it doesn't due to the fact the Uri is escaped. So I've patched up that too:
public static string MakeRelativePath(string basePath, string tgtPath) {
return
Uri.UnescapeDataString(
new Uri(basePath, UriKind.Absolute)
.MakeRelativeUri(new Uri(tgtPath, UriKind.Absolute))
.ToString()
).Replace('/', Path.DirectorySeparatorChar);
}
This versions seems to work, but it leaves me feeling a little quesy: aren't there any valid local filesystem paths that this gratuitous unescaping might corrupt?
Related: How to get relative path from absolute path The answers to that question do not address the issue of unusual characters and escaping at all, and as such don't answer this question.