Reputation: 211
This question is similar: Possible to specify directory path with a wildcard?
However in my case I want to obtain all files from every single folder named 'data' that is a first child of all folders in my directory.
Hypothetically what I would need is the following:
string[] files = System.IO.Directory.GetFiles(directory + "\\Share\\*\\data");
*'directory' is simply a string of the directory path
Wildcards are not accepted in both GetFiles and GetDirectories methods and it is my understanding, they must be used as filters as a second parameter (both these methods have that overload). However in the GetFiles case, it is specifically to filter files and not directories, and in the GetDirectories case, it is giving me the same error, as if the filter was only applicable on the lowest level directories (or something of the sort).
I could do this with multiple calls to GetDirectories and GetFiles in a loop, but I'd rather find a more elegant solution. (i.e. What I want to avoid:: Get all directories under my directory\Share, loop through and add get all files for each \data directory of those, agglomerate all of that into a list of strings for my file names etc...)
EDIT - SOLUTION:: Actually @Steve Wong pointed me towards the solution I went with (hopefully regexes aren't a big no-no):
Regex reg = new Regex(@"^\\" + directory + @"\\Share\\.*\\data\\.*\.xml$");
List<string> files = System.IO.Directory.GetFiles(connect + "\\Share","*.*",SearchOption.AllDirectories).Where(path => reg.IsMatch(path)).ToList();
Thanks for the help!
Upvotes: 1
Views: 3367
Reputation: 2256
You could try this:
string rootDirectory = directory + "\\Share\\";
var files = Directory.GetDirectories(rootDirectory, "*", SearchOption.AllDirectories).Where(
(directoryPath) => StringComparer.OrdinalIgnoreCase.Compare(Path.GetFileName(directoryPath), "Data") == 0).SelectMany(
(directoryPath) => Directory.GetFiles(directoryPath, "*"));
The Where clause will return all folder paths that end with a "Data/data" folder, and then the SelectMany returns all files in those folders.
Upvotes: 1