In C#, how do I combine more than two parts of a file path at once?

Matthew picture Matthew · Jan 3, 2010 · Viewed 13.6k times · Source

To combine two parts of a file path, you can do

System.IO.Path.Combine (path1, path2);

However, you can't do

System.IO.Path.Combine (path1, path2, path3);

Is there a simple way to do this?

Answer

Aaronaught picture Aaronaught · Jan 3, 2010

Here's a utility method you can use:

public static string CombinePaths(string path1, params string[] paths)
{
    if (path1 == null)
    {
        throw new ArgumentNullException("path1");
    }
    if (paths == null)
    {
        throw new ArgumentNullException("paths");
    }
    return paths.Aggregate(path1, (acc, p) => Path.Combine(acc, p));
}

Alternate code-golf version (shorter, but not quite as clear, semantics are a bit different from Path.Combine):

public static string CombinePaths(params string[] paths)
{
    if (paths == null)
    {
        throw new ArgumentNullException("paths");
    }
    return paths.Aggregate(Path.Combine);
}

Then you can call this as:

string path = CombinePaths(path1, path2, path3);