Tuesday, May 16, 2006

Finally! .NET 2.0 Directory Search Improvements

This may seem insignificant to most, but I was thrilled to see that Microsoft added a static method overload to the Directory.GetFiles() method to include a recursive "SearchOption", which specifies whether the search should return files in only the current directory or search through all subdirectories as well.

public static string[] GetFiles (
string path,
string searchPattern,
SearchOption searchOption
)


But, before I got too excited, I found they still don't allow multiple search patterns. You must make a call for each pattern you are searching for. :-(

Still, this improvement saves having to write or reuse that recursive directory search function you've been using forever. It also allows for quick and easy accumulation of files into a collection. For example:
           
ArrayList files = new ArrayList();
try
{
files.AddRange(Directory.GetFiles(@"C:\", "*.jpg",
SearchOption.AllDirectories));
files.AddRange(Directory.GetFiles(@"C:\", "*.bmp",
SearchOption.AllDirectories));
files.AddRange(Directory.GetFiles(@"C:\", "*.tif?",
SearchOption.AllDirectories));
}
catch (UnauthorizedAccessException expectedException)
{
}

As small as this change seems, it's a welcome change!

Terry

No comments: