File globbing in .NET

January 26th 2024 .NET

Glob patterns are a cross-platform standard approach for specifying sets of filenames. There is no built-in support for them in the base class library, but you can choose from multiple NuGet packages.

The most common way for enumerating a set of files in .NET is the Directory.GetFiles method. Even this method has limited support for search patterns:

var matchingFiles = Directory.GetFiles(".", "Sleep/sleep-*.json");

However, you can't use the full glob syntax with it. Wildcards are only supported in the filename part of the pattern, and even there you can only use * and ?. Trying to use unsupported patterns, such as **/*.json, will result in an exception:

The filename, directory name, or volume label syntax is incorrect. : c:\Users\damir\Temp\**

A better choice for adding glob patterns support to your application is the Microsoft.Extensions.FileSystemGlobbing NuGet package. You can then use the Matcher class and its extension methods to enumerate the matching files:

var matcher = new Matcher();
matcher.AddInclude("**/*.json");
var matchingFiles = matcher.GetResultsInFullPath(".");

The exact set of supported pattern formats is well documented.

If you need support for an even broader set of patterns, take a look at the Glob NuGet package and its Glob class:

var matchingFiles = Glob.Files(".", "Sleep/sleep-202?-0[1-9]-*.json");

You can use a sample project from my GitHub repository to try out and compare all 3 different approaches.

If you want to add support for filtering files in your application, consider using glob patterns instead of regular expressions because users will most likely be more familiar with them. You have multiple options to implement them in .NET. Choose the one that best suits your requirements.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License