Tuesday, February 05, 2008

I've found myself wishing that I could pass in more than two arguments to Path.Combine. That is, something like this:

Path.Combine(rootPath, someCalculatedPath, someKnownFileName);

As it is, Path.Combine only accepts two arguments, so I end up with calls that look like this:

Path.Combine(Path.Combine(rootPath, comeCalculatedPath), someKnownFileName);

It seems like a hassle to me. Here is a simple wrapper function (with accompanying test) that will accomplish this:

public static class FileUtils
{
    public static string CombinePaths(params string[] paths)
    {
        if (paths.Length == 0) return string.Empty; 

        return Path.Combine(paths.First(), CombinePaths(paths.Skip(1).ToArray()));
    }
} 

[TestFixture]
public class FileUtilsTests
{
    [Test]
    public void Should_combine_paths_correctly()
    {
        string expected = @"c:\some\path\to\file.txt"; 

        Assert.AreEqual(expected, FileUtils.CombinePaths("c:\\some", "path\\to", "file.txt"));
    }
}
Tuesday, February 05, 2008 3:41:46 PM (Central Standard Time, UTC-06:00)
Y'know, this would be one example of where a "static extension method" would be handy, if such a beast existed. Then you could simply add your own overload of the static Combine method to the Path class.

Of course, I have no idea what the syntax for defining a static extension method would be. :) Maybe using generics somehow:

public static string Combine<this Path>(params string[] paths)
{
/* ... */
}
Tuesday, February 05, 2008 4:42:12 PM (Central Standard Time, UTC-06:00)
True, true :)

My initial argument was going to be that we're not on 3.5 yet so we can't use extension methods, but that argument won't fly because my sample solution uses the extension methods off of IEnumerable<T>!

*sigh*
Comments are closed.