Does there exist a method in C# to get the relative path given two absolute path inputs? [duplicate]
Does there exist a method in C# to get the relative path given two absolute path inputs?
That is I would have two inputs (with the first folder as the base) such as
c:\temp1\adam\
and
c:\temp1\jamie\
Then the output would be
..\jamie\
Not sure if there is a better way, but this will work:
var file1 = @"c:\temp1\adam\";
var file2 = @"c:\temp1\jamie\";
var result = new Uri(file1)
.MakeRelativeUri(new Uri(file2))
.ToString()
.Replace("/", "\\");
this is simple. Steps:
- Remove common beginning of string (
c:\temp1\
) - Count number of directories of first path (1 in your case)
- Replace them with ..
- Add second path
Updated: since the constructor is now obsolete you can use:
Uri.UnescapeDataString(new Uri(file1).MakeRelativeUri(new Uri(file2)).ToString())
.Replace("/", "\\");
old version:
Kirk Woll's idea is good but you need to ensure your path doesn't get mangled (e.g. spaces replaced by %20) by telling Uri not to escape your path:
var result = new Uri(file1, true)
.MakeRelativeUri(new Uri(file2, true))
.ToString()
.Replace("/", "\\");
精彩评论