Managed Extensions: Finding Files by Extension

Welcome to this week's installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer demonstrates how to perform a practical .NET programming task using either C# or Managed C++ Extensions.

A reader recently asked me how to locate all files with a specific extension so that he could register those files with his application. Basically, all he needs to do is allow the user to specify where he wants the search to begin (accomplished with the .NET FolderBrowserDialog component) and then have a recursive function enumerate each folder and compare the searched-for file extension with the extension of each file found. The "matching" files are returned to the caller in an ArrayList object. Figure 1 shows an example of a demo application I wrote to illustrate this:

Folder-Browser Dialogs in .NET

Many C++ classes today allow you to display a folder-browser dialog. However, if you had to perform this task (using the Shell API function SHBrowseForFolder) before C++ helper classes and better documentation existed, you'll be happy to note that this task is much easier in .NET (specifically Windows Forms applications). For this article's attached demo, I did the following:

I opened the form whose class will use the folder browser.

I opened the Toolbox and dragged a FolderBrowserDialog control onto the form. (I positioned it below the form, as it's a class and not a UI element.)

I specified the needed properties. IntelliSense helped here, but the most commonly specified ones were things like Description (the text that will display on the dialog above the folder list), ShowNewFolderButton (a property that allows you to specify if you want the user to be able to create folders while browsing), and RootFolder (whose value is used to specify the top-level folder that the user cannot exceed). The demo's Form::Load method has the following initialization: