Find files that match multiple patterns in C#

[find files]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in .NET, files and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *