Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a directory string from component parts in C#

If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?

I know of

Path.Combine
but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.

e.g:

string folder1 = "foo";
string folder2 = "bar";

CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")

Any ideas? Does C# support unlimited args in methods?

like image 621
Gary Willoughby Avatar asked Sep 27 '08 20:09

Gary Willoughby


2 Answers

Does C# support unlimited args in methods?

Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested):

string CombinePaths(params string[] parts) {
    string result = String.Empty;
    foreach (string s in parts) {
        result = Path.Combine(result, s);
    }
    return result;
}
like image 118
OregonGhost Avatar answered Sep 22 '22 23:09

OregonGhost


LINQ to the rescue again. The Aggregate extension function can be used to accomplish what you want. Consider this example:

string[] ary = new string[] { "c:\\", "Windows", "System" };
string path = ary.Aggregate((aggregation, val) => Path.Combine(aggregation, val));
Console.WriteLine(path); //outputs c:\Windows\System
like image 32
Jason Jackson Avatar answered Sep 21 '22 23:09

Jason Jackson