Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 432
Matthew Avatar asked Jan 03 '10 20:01

Matthew


People also ask

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.

What is '~' in C programming?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What is operators in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.


2 Answers

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); 
like image 132
Aaronaught Avatar answered Sep 28 '22 23:09

Aaronaught


As others have said, in .NET 3.5 and earlier versions there hasn't been a way to do this neatly - you either have to write your own Combine method or call Path.Combine multiple times.

But rejoice - for in .NET 4.0, there is this overload:

public static string Combine(     params string[] paths ) 

There are also overloads taking 3 or 4 strings, presumably so that it doesn't need to create an array unnecessarily for common cases.

Hopefully Mono will port those overloads soon - I'm sure they'd be easy to implement and much appreciated.

like image 38
Jon Skeet Avatar answered Sep 29 '22 00:09

Jon Skeet