Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Path.Combine be used with more than two arguments?

Tags:

I'm surprised there's not an overload that can take a string array. Anyway, what is the best way to avoid nesting calls to Path.Combine?

pathValue = Path.Combine(path1, Path.Combine(path2, Path.Combine(path3, path4))) 

This seems inefficient since it results in four new strings being created just to get one.

like image 942
Rob Sobers Avatar asked Apr 17 '09 14:04

Rob Sobers


2 Answers

If you already have an array or an IEnumerable<T> then you could do this in one line...

// I'm assuming that you've got an array or IEnumerable<T> from somewhere var paths = new string[] { path1, path2, path3, path4, path5, path6 };  string result = paths.Aggregate(Path.Combine); 

If not, then write your own extension method to string...

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

... that would allow you to chain these like this...

string result = path1.CombinePathWith(path2)                      .CombinePathWith(path3)                      .CombinePathWith(path4)                      .CombinePathWith(path5)                      .CombinePathWith(path6); 
like image 61
Martin Peck Avatar answered Sep 27 '22 19:09

Martin Peck


The efficiency side of things isn't the problem IMO - it's the usability side of things. Personally I think there ought to be an overload of:

Combine(string first, string second, string third, params string[] others) 

You need to have at least three to prevent it from clashing with the existing two-parameter version if you just write Path.Combine("foo", "bar") but it would certainly help to make code clearer. Why not open a feature request on Connect?

Of course, you can implement this yourself (and in another class the number of parameters doesn't matter so much):

public static string CombinePaths(string first, params string[] others) {     // Put error checking in here :)     string path = first;     foreach (string section in others)     {         path = Path.Combine(path, section);     }     return path; } 
like image 26
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet