I am building a Windows application in Visual Studio 2012 in C# and .net 4.0.
One of the functions of the program is to search for all files that meet a given search criteria, which usually (but doesn't always) include wildcards.
The search criteria is unknown at run time; it is imported from an excel spreadsheet.
Possible search criteria can include the following:
- Exact path
- "C:\temp\directory1\directory2\someFile.txt"
- Path, with wildcards in the filename:
- "C:\temp\directory1\directory2*.*"
- Filename, with wildcards in the path:
- "C:\temp*\directory*\someFile.txt"
- Filename and path with wildcards:
- "C:\temp\*\*\*.*"
- All of the above, with arbitrary directory structure:
- "C:\temp\dir*1\dir*\anotherdir\*\another*\file*.txt"
- "C:\te*\*\someFile.txt"
- "C:\temp\*tory1\dire*2\*\*\*\*\*.*"
I've attempted to use Directory.EnumerateFiles
:
IEnumerable<string> matchingFilePaths = System.IO.Directory.EnumerateFiles(@"C:\", selectedItemPath[0], System.IO.SearchOption.AllDirectories);
However this only works with Case 2 above. Attempting to use Directory.EnumerateFiles
with wildcards in the folder names causes an "Illegal Character" exemption.
I'm hoping there's a one-liner in .net I can use to do this file searching. The number of wildcards and the depth of the directory structure is unknown at run time, and it's conceivable that the search might have to go a hundred folders deep, with every folder containing an unknown number of wildcards. (This is the crux of the problem). Trying to avoid having an insane number of nested for loops as well.
I read the solutions here but this doesn't seem to work for an arbitrary folder structure.