Directory.GetFiles with Multiple Extensions in C# (.NET 10)

C# Directory.GetFiles returns the full paths of the files in a folder, and its search pattern accepts one wildcard pattern such as *.txt, not several. You need every .txt and .dat file in a folder, and Directory.GetFiles takes only one search pattern. There is no "*.txt|*.dat" form, so multiple extensions need a different approach. The fix is to get the files and filter the extension yourself, or to call the method once per pattern. This article shows both, plus how to include subfolders, ignore case, and match file names with a regular expression. Every sample was compiled and run on .NET 10, and the output below is real.

Animated table of what you want and which call to use: one extension uses GetFiles with a pattern, several extensions use EnumerateFiles with a HashSet of extensions, subfolders use SearchOption.AllDirectories, ignoring case uses OrdinalIgnoreCase or MatchCasing, and name patterns use Regex on the file name. It is an illustration, not a screenshot.
Which call to use for each need (illustration, not a screenshot).

C# Directory.GetFiles: get all files from a folder

Directory.GetFiles(path) returns a string[] with the full path of each file directly inside path. It does not look into subfolders unless you ask. The order is not guaranteed, so sort the result if order matters (Directory.GetFiles (Microsoft Learn)).

string[] files = Directory.GetFiles(path);
Console.WriteLine(files[0]);   // <root>/a.txt  (the full path, not just the name)

Use Path.GetFileName(file) when you only want the name. To get the newest file instead of all of them, see find the most recent files in a directory.

C# GetFiles search pattern: filter by one extension

The second argument is a search pattern. It supports the wildcards * and ? and does not support regular expressions (Directory.GetFiles (Microsoft Learn)). For one extension, put it after *.:

Directory.GetFiles(path, "*.txt");                              // top folder only
Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);  // include subfolders

My test folder had a.txt, Report_Insert_01.txt, UPPER.TXT and sub/d.txt. The first call returned the three top-level files, the second added sub/d.txt. On this Mac the pattern matched UPPER.TXT too, because matching uses the platform default casing (MatchCasing.PlatformDefault). I only ran macOS, and on Linux the same pattern can behave differently. The EnumerationOptions section below shows how to make it explicit.

Two older habits are worth dropping. The pattern "*.txt*" from older samples works but means “extension starts with txt”, so it also matches .txtx. Use "*.txt". And "*.*" is the same as no pattern at all.

The three-letter extension quirk

Microsoft documents that in .NET Framework a pattern such as "*.xls" also returns book.xlsx, because it matches a three-character extension as a prefix. In .NET 5 and later it returns only book.xls (Directory.GetFiles (Microsoft Learn)). I ran it on .NET 10 with old.xls and new.xlsx in the folder and got only old.xls. I did not run .NET Framework here.

Directory.GetFiles with multiple extensions

The old way was to fetch everything and filter with EndsWith:

var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
    .Where(s => s.EndsWith(".txt") || s.EndsWith(".dat"));

It works but has a real bug: EndsWith(string) compares with the current culture and is case-sensitive, so UPPER.TXT is missed. In my run this version returned five files and skipped UPPER.TXT. A better version keeps the wanted extensions in a HashSet that ignores case and checks each file with Path.GetExtension (Microsoft Learn):

var wanted = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".txt", ".dat" };

IEnumerable<string> files = Directory
    .EnumerateFiles(path, "*", SearchOption.AllDirectories)
    .Where(f => wanted.Contains(Path.GetExtension(f)));

EnumerateFiles returns results as it walks the folder instead of building the whole array first, which Microsoft notes can be more efficient with many files (Directory.EnumerateFiles (Microsoft Learn)). Use .ToArray() if you need an array.

SearchOption.AllDirectories and TopDirectoryOnly

SearchOption.TopDirectoryOnly (value 0, the default) searches only the folder you pass. SearchOption.AllDirectories (value 1) also searches every subfolder. With the HashSet filter above, my test folder gave these results:

AllDirectories   a.txt, b.dat, Report_Insert_01.txt, sub/d.txt, sub/Job_Insert_02.dat, UPPER.TXT
TopDirectoryOnly a.txt, b.dat, Report_Insert_01.txt, UPPER.TXT

Several patterns, one call each

If you prefer the file system to do the matching, call the method once per pattern and merge. Add Distinct() in case the patterns overlap:

string[] patterns = { "*.csv", "*.jpg", "*.dat" };
var files = patterns
    .SelectMany(p => Directory.EnumerateFiles(path, p, SearchOption.AllDirectories))
    .Distinct();
// b.dat, c.csv, sub/e.jpg, sub/Job_Insert_02.dat

This walks the folder tree once per pattern, so for many extensions or a large tree the single walk with a HashSet is cheaper.

EnumerationOptions: case, errors and recursion in one object

Since .NET Core 2.1 you can pass an EnumerationOptions object instead of SearchOption (EnumerationOptions (Microsoft Learn)). It lets you choose casing, skip folders you cannot read, and recurse:

var options = new EnumerationOptions
{
    RecurseSubdirectories = true,
    IgnoreInaccessible = true,                 // skip folders you have no permission for
    MatchCasing = MatchCasing.CaseInsensitive  // same result on Windows, macOS and Linux
};

foreach (var f in Directory.EnumerateFiles(path, "*.txt", options))
    Console.WriteLine(f);
// a.txt, Report_Insert_01.txt, sub/d.txt, UPPER.TXT

IgnoreInaccessible matters in real folders: without it, one locked subfolder can throw UnauthorizedAccessException and stop the whole search.

Filter file names with a regex pattern

Search patterns cannot be regular expressions, so get the files first and test the file name (not the full path) with Regex. This keeps only names that contain _Insert_:

using System.Text.RegularExpressions;

var rx = new Regex(@"^.*_Insert_.*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));

var files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
    .Where(f => rx.IsMatch(Path.GetFileName(f)));
// Report_Insert_01.txt, sub/Job_Insert_02.dat

The older version of this article printed the pattern as @"^._<em>Insert_.</em>", which is a formatting accident and does not work. The correct pattern is ^.*_Insert_.*$. The match timeout of one second protects against slow patterns on odd file names. For a plain “contains” test you do not need a regex: Path.GetFileName(f).Contains("_Insert_", StringComparison.OrdinalIgnoreCase) is simpler. Related file tasks: get a file’s last modified date, get file size in C# and merge multiple files into one.

Common problems

  • DirectoryNotFoundException. The folder does not exist. Check Directory.Exists(path) first.
  • UnauthorizedAccessException with AllDirectories. A subfolder is not readable. Use EnumerationOptions with IgnoreInaccessible = true.
  • Files missing on Linux. Pattern and extension checks can be case-sensitive there. Use MatchCasing.CaseInsensitive or StringComparer.OrdinalIgnoreCase.
  • Results are full paths. Use Path.GetFileName or Path.GetRelativePath for display.

What was tested and what was not

  • Run on macOS with .NET SDK 10.0.401: every snippet above against a temporary folder holding ten files (including UPPER.TXT, old.xls, new.xlsx and a sub folder). The result lines quoted are the real output, with the temporary folder removed from the paths.
  • Not tested: Windows or Linux (the note about case rules and the 8.3 name quirk comes from Microsoft’s documentation), .NET Framework, network shares, folders with no read permission, and very large trees.

Summary

  • GetFiles takes one wildcard pattern, never a list and never a regex.
  • For several extensions, enumerate once and filter with a case-insensitive HashSet and Path.GetExtension, or call once per pattern and merge.
  • Use SearchOption.AllDirectories or EnumerationOptions for subfolders, and test regex on the file name only.

Found this useful?

Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

Directory.GetFiles FAQ

How do I use Directory.GetFiles with multiple extensions in C#?

You cannot put several extensions in one pattern, because the search pattern supports only the wildcards * and ?. Filter by extension after getting the files, or call the method once for each pattern.

What is the C# Directory.GetFiles search pattern syntax?

A literal name with the wildcards * (any characters) and ? (one character), for example *.txt. It does not support regular expressions; test the file name with Regex after getting the files.

What is the difference between GetFiles and EnumerateFiles?

GetFiles returns the full array after the search finishes. EnumerateFiles returns results as it finds them, which Microsoft says can be more efficient for many files. Both give full paths.

Which filter did you need? Tell us in the comments if a case is missing.

2 thoughts on “Directory.GetFiles with Multiple Extensions in C# (.NET 10)”

    1. Hello TJ- Please use regex with GetFile method as below,
      Regex reg = new Regex(@”^.*_Insert_.*”);
      var result = Directory.GetFiles(path, “*.txt”).Where(path => reg.IsMatch(path)).ToArray();
      Hope it helps.i added this to example list above.

Leave a Reply

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