tags:

views:

167

answers:

1

I'm hoping there is a built in .NET method to do this, but I'm not finding it.

I have two paths that I know to be on the same root drive, I want to be able to get a relative path from one to the other.

string path1 = @"c:\dir1\dir2\";
string path2 = @"c:\dir1\dir3\file1.txt";
string relPath = MysteryFunctionThatShouldExist(path1, path2); 
// relPath == "..\dir3\file1.txt"

Does this function exist? If not what would be the best way to implement it?

+19  A: 

Uri works:

Uri path1 = new Uri(@"c:\dir1\dir2\");
Uri path2 = new Uri(@"c:\dir1\dir3\file1.txt");
Uri diff = path1.MakeRelativeUri(path2);
string relPath = diff.OriginalString;
Marc Gravell
Uri does work but will switch to forward slashes, which is easy enough to fix. Thanks!
Bert Lamb