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.

2 Responses to Find files that match multiple patterns in C#

  1. anne says:

    Hi Rod,

    Thank you for this code.

    I tried your code and it seems to work properly. However, there is a small problem because if you decide to display only .xls files from a directory that contains .xls and .xlsx files the code will display the .xlsx files too.

    • RodStephens says:

      That’s a feature of the way Directory.GetFiles works. File Explorer also works that way.

      If you really want .xls files and not .xlsx files, I think you’re going to need to filter the returned files yourself. You could loop through them yourself or use lINQ.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.