.NET Version 4 adds support for filename globs to the Directory
class. The 2- and 3-argument variants of methods like GetFiles()
and EnumerateDirectories()
take a search string as their second argument that supports filename globbing, with both *
and ?
.
class GlobTestMain
{
static void Main(string[] args)
{
string[] exes = Directory.GetFiles(Environment.CurrentDirectory, "*.exe");
foreach (string file in exes)
{
Console.WriteLine(Path.GetFileName(file));
}
}
}
would yield
GlobTest.exe
GlobTest.vshost.exe
The docs state that there are some caveats with matching extensions. It also states that 8.3 file names are matched (which may be generated automatically behind the scenes), which can result in "duplicate" matches in given some patterns.
If you can't use version 4 in your (or your clients') environments, you probably have to use Regexes.
The methods that support this are GetFiles()
, GetDirectories()
, and GetFileSystemEntries()
. The Enumerate
variants also support this.