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.Combinebut 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?
Try this one:
The params makes it so that you can append an infinite amount of strings.
Path.Combine does is to make sure that the inputted strings does not begin with or ends with slashes and checks for any invalid characters.
LINQ to the rescue again. The Aggregate extension function can be used to accomplish what you want. Consider this example:
I prefer to use DirectoryInfo vs. the static methods on Directory, because I think it's better OO design. Here's a solution with DirectoryInfo + extension methods, that I think is quite nice to use:
I don't love the fact that I'm modifying
self
, but for this short method, I think it's cleaner than making a new variable.The call site makes up for it, though:
Adding a way to get a FileInfo is left as an exercise (for another SO question!).
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):