A pedant that hangs out in the dark corner-cases of the web.

Wednesday, September 26, 2007

Globbing (using filename wildcard patterns) in C#

The Directory.GetFiles() method in the .NET CLR is unsatisfying for anyone that just wants to use simple filename wildcard patterns. Before you can even call GetFiles(), there are several steps you have to perform manually. Minimally, you have to split the directory from the filename pattern, then you have to convert the directory to an absolute path. If you want to process an array of delimited pattern lists, there are even more steps. Here's a simple recipe:

public static class Glob
{
static public string[] GetFiles(string[] patterns)
{
List<string> filelist= new List<string>();
foreach(string pattern in patterns)
filelist.AddRange(GetFiles(pattern));
string[] files= new string[filelist.Count];
filelist.CopyTo(files,0);
return files;
}

static public string[] GetFiles(string patternlist)
{
List<string> filelist= new List<string>();
foreach(string pattern in
patternlist.Split(Path.GetInvalidPathChars()))
{
string dir= Path.GetDirectoryName(pattern);
if(String.IsNullOrEmpty(dir)) dir=
Directory.GetCurrentDirectory();
filelist.AddRange(Directory.GetFiles(
Path.GetFullPath(dir),
Path.GetFileName(pattern)));
}
string [] files= new string[filelist.Count];
filelist.CopyTo(files,0);
return files;
}
}

This only resolves patterns in filenames, not paths, but may serve the needs for this common task for most uses, and provides a starting point for something more comprehensive.