Resolving relative paths in C#

February 24, 2010

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.