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.

4 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

top [url=http://www.c-online-casino.co.uk/]uk casino bonus[/url] check the latest [url=http://www.casinolasvegass.com/]casino games[/url] unshackled no consign hand-out at the foremost [url=http://www.baywatchcasino.com/]bay take note of casino
[/url].

Anonymous said...

hey there and thank you for your information – I have certainly picked up
something new from right here. I did however expertise several technical points using this web site,
since I experienced to reload the web site many times previous to I could get it to load properly.
I had been wondering if your web hosting is OK? Not that I'm complaining, but slow loading instances times will often affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Anyway I'm adding this
RSS to my e-mail and could look out for a lot more of your
respective intriguing content. Ensure that you update this again very soon.


Also visit my website ... ra law group scam

Anonymous said...

Ahaa, its good discussion concerning this article here at
this webpage, I have read all that, so at this time me also commenting at this place.


Also visit my webpage ... book of ra kostenlos spielen
deutsch ()