Title: Find files that match multiple patterns in C#
The System.IO.Directory.GetFiles method lets you easily search for files in a directory that match a pattern. Unfortunately it can only search for files that match a single pattern. For example, if you want to find files that match the patterns *.bmp, *.gif, *.jpg, and *.png, you're out of luck.
The FindFiles method shown in the following code searches for files that match multiple patterns.
// Search for files matching the patterns.
private List<string> FindFiles(string dir_name, string patterns,
bool search_subdirectories)
{
// Make the result list.
List<string> files = new List<string>();
// Get the patterns.
string[] pattern_array = patterns.Split(';');
// Search.
SearchOption search_option = SearchOption.TopDirectoryOnly;
if (search_subdirectories)
search_option = SearchOption.AllDirectories;
foreach (string pattern in pattern_array)
{
foreach (string filename in Directory.GetFiles(
dir_name, pattern, search_option))
{
if (!files.Contains(filename)) files.Add(filename);
}
}
// Sort.
files.Sort();
// Return the result.
return files;
}
The method creates an output List and then splits its patterns parameter into an array of separate pattern strings. Then for each pattern, the code uses Directory.GetFiles to search for files matching the pattern. If a matching file is not yet in the result list, the code adds it. The method finishes by sorting and returning the results.
Download the example to experiment with it and to see additional details.
|