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

September 23. 2011 14:57

pingback

Pingback from freerob.com

HTML | Free Software | Free Templates | Freerob.com

freerob.com

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading