Finding a Relative Path in .NET

Posted by Rick Strahl on West-Wind See other posts from West-Wind or by Rick Strahl
Published on Tue, 21 Dec 2010 02:17:34 GMT Indexed on 2010/12/21 5:00 UTC
Read the original article Hit count: 6168

Filed under:
|

Here’s a nice and simple path utility that I’ve needed in a number of applications: I need to find a relative path based on a base path. So if I’m working in a folder called c:\temp\templates\ and I want to find a relative path for c:\temp\templates\subdir\test.txt I want to receive back subdir\test.txt. Or if I pass c:\ I want to get back ..\..\ – in other words always return a non-hardcoded path based on some other known directory.

I’ve had a routine in my library that does this via some lengthy string parsing routines, but ran into some Uri processing today that made me realize that this code could be greatly simplified by using the System.Uri class instead. Here’s the simple static method:

/// <summary>
/// Returns a relative path string from a full path based on a base path
/// provided.
/// </summary>
/// <param name="fullPath">The path to convert. Can be either a file or a directory</param>
/// <param name="basePath">The base path on which relative processing is based. Should be a directory.</param>
/// <returns>
/// String of the relative path.
/// 
/// Examples of returned values:
///  test.txt, ..\test.txt, ..\..\..\test.txt, ., .., subdir\test.txt
/// </returns>
public static string GetRelativePath(string fullPath, string basePath ) 
{
    // ForceBasePath to a path
    if (!basePath.EndsWith("\\"))
        basePath += "\\";

    Uri baseUri = new Uri(basePath);
    Uri fullUri = new Uri(fullPath);

    Uri relativeUri = baseUri.MakeRelativeUri(fullUri);

    // Uri's use forward slashes so convert back to backward slashes
    return relativeUri.ToString().Replace("/", "\\");

}

You can then call it like this:

string relPath = FileUtils.GetRelativePath("c:\temp\templates","c:\temp\templates\subdir\test.txt")

It’s not exactly rocket science but it’s useful in many scenarios where you’re working with files based on an application base directory. Right now I’m working on a templating solution (using the Razor Engine) where templates live in a base directory and are supplied as relative paths to that base directory. Resolving these relative paths both ways is important in order to properly check for existance of files and their change status in this case.

Not the kind of thing you use every day, but useful to remember.

© Rick Strahl, West Wind Technologies, 2005-2010
Posted in .NET  CSharp  
kick it on DotNetKicks.com

© West-Wind or respective owner

Related posts about .NET

Related posts about CSharp