Say you have a string with a file name with a relative path, such as “..\..\somedir\somefile.txt”, and you want to resolve the full path to the file given a certain reference point in the file system, how would you go about to solve that. Turns out it is rather simple: System.Uri has relative path resolving powers:

public static string ResolveRelativePath(string referencePath, string relativePath) 
{ 
    Uri uri = new Uri(Path.Combine(referencePath, relativePath)); 
    return Path.GetFullPath(uri.AbsolutePath); 
}

Now you can resolve the path like this:

// path will contain "c:\directory\anothersubdir\somefile.txt"
string path = ResolveRelativePath(@"c:\directory\subdir", @"..\anothersubdir\somefile.txt");

Update: As Morgan points out in the comments, using System.Uri is actually not necessary. The following code will do the same job (but in a more efficient manner):

public static string ResolveRelativePath(string referencePath, string relativePath) 
{ 
    return Path.GetFullPath(Path.Combine(referencePath, relativePath));
}

I shall spend a moment in the corner of shame for not doing that from the start.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Comments

February 24. 2010 11:11

trackback

Resolving relative paths in C#

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com

February 24. 2010 11:20

Morgan

If you only work with paths on disk, then you can skip the Uri class and do Path.GetFullPath(Path.Combine(referencePath, relativePath));

Morgan

February 24. 2010 11:38

fredrik

@Morgan: wow, how could I ever miss that one. I feel ashamed.

fredrik

August 7. 2012 17:08

Håkan Fröling

O my, I have done the same program, but I get stuck when the combined path is to long... the GetFullPath throws an exception. Any sugestions?

Håkan Fröling

August 7. 2012 19:34

fredrik

Håkan, I think the only reasonable way is to catch the PathTooLongException and handle it as gracefully as possible.

fredrik

September 10. 2012 16:26

Yomodo

Hi, AlphaFS can handle "Paths that are Too Long" nicely.

Please see: http://alphafs.codeplex.com/

Yomodo

November 26. 2012 20:27

jimkoteni

Thanks

jimkoteni