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

Bookmark and Share

Comments

February 24. 2010 06:11

trackback

Resolving relative paths in C#

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

DotNetKicks.com

February 24. 2010 06: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 06:38

fredrik

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

fredrik

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading