Monday, October 23, 2006
« Regular Expression Tester Application | Main | UCNUG Presentation on Refactoring »

This might be useful to someone out there.  I had had this issue many months ago, but had to resolve it again today because I hadn't jotted down the solution - fortunately it only took about 2 minutes.

I am making use of the FolderBrowserDialog class in the .NET 2.0 Framework.  This class, as it's name implies, provides a graphical interface for browsing and selecting folders.

The issue was that when i made my call to .ShowDialog(), the dialog would appear but it was blank - only the 'Make New Folder', 'OK', and 'Cancel' buttons along with the description were visible, but the folder TreeView was not.  This would have worked from the get-go had a created my project as a Windows Forms project but I didn't; it's a Console application.

To solve the problem, I simply had to add the [STAThread()] to my Main() method - now it works like a charm.

[STAThread()]
public static void Main() {
   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);
   Application.Run(new TestForm());
}

// ...then on the TestForm class

private void btnBrowseForFolder_Click(object sender, EventArgs e) {
   string folderPath = browseForFolder();
   // do something with the result
}

private string browseForFolder() {
   using ( FolderBrowserDialog dlg = new FolderBrowserDialog() ) {
      dlg.Description = "Select a folder";
      dlg.ShowNewFolderButton = true;
      dlg.RootFolder = Environment.SpecialFolder.MyComputer;
      return ( DialogResult.OK == dlg.ShowDialog(this) )
         ? dlg.SelectedPath
         : null;
   }
}