16

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\
Matt
  • 25,943
  • 66
  • 198
  • 303

3 Answers3

10

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("/", "\\");
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
2

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("/", "\\");
laktak
  • 57,064
  • 17
  • 134
  • 164
  • Hmm, I thought this was a good point, but it bears mentioning that that constructor is considered obsolete and will generate a compiler warning. In my testing, I did not have any issues with escaped characters. I wonder what characters were being escaped for you? – Kirk Woll May 02 '13 at 17:20
  • @Kirk Woll, I had problems with spaces in the name. – laktak May 02 '13 at 20:16
  • Ah, duh, sorry, didn't realize you had mentioned that. Thanks for responding. – Kirk Woll May 02 '13 at 20:17
2

this is simple. Steps:

  1. Remove common beginning of string (c:\temp1\)
  2. Count number of directories of first path (1 in your case)
  3. Replace them with ..
  4. Add second path
Andrey
  • 59,039
  • 12
  • 119
  • 163
  • 2
    but you don't know the common prefix! (step 1) – Mitch Wheat Nov 02 '10 at 00:15
  • 1
    Finding the common prefix of two strings isn't that hard. The problem lies in the details. Both / and \ are path seperators, some filesystems are case-insensitive, others are case-sensitive, a path can contain . or .. and probably several other issues. On the other hand underestimating the common part isn't that big a problem. – CodesInChaos Nov 02 '10 at 01:13
  • @Mitch Wheat i thought it is obvious – Andrey Nov 02 '10 at 11:09
  • @CodeInChaos: i didn't say it was hard. – Mitch Wheat Nov 02 '10 at 12:04