Building Paths Fluently

If you ever need to “build” a path (i.e. “C:\folder1\subfolder”), you really should be using Path.Combine.  It makes sure the trailing directory separator is in between the two paths (and it puts the appropriate character in – DirectorySeparatorChar).  I wanted an easier way to build a path than having to constantly call Path.Combine so I created a handy little extension method that lets me build paths “fluently”:

public static string PathCombine(this string path1, string path2)
{
    return Path.Combine(path1, path2);
}

Now I can write code like this:

var dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    .PathCombine("Folder1")
    .PathCombine("Folder2");

Technorati Tags: ,,

3 Comments

Comments have been disabled for this content.