1

I have created an application compiled with .NET 3.5. and used the FolderBrowserDialog object. When a button is pressed I execute this code:

FolderBrowserDialog fbd = new FolderBrowserDialog ();
fbd.ShowDialog();

A Folder dialog is shown but I can't see any folders. The only thing I see are the buttons OK & Cancel (and create new folder button when the ShowNewFolderButton properyty is set to true). When I try the exact same code on a different form everything is working fine.

Any ideas??

Aditya Korti
  • 692
  • 2
  • 12
  • 28
subash
  • 4,050
  • 14
  • 51
  • 78

1 Answers1

1

Check that the thread running your dialog is on an STAThread. So for example make sure your Main method is marked with the [STAThread] attribute:

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

Otherwise you can do this (from the Community Content on FolderBrowserDialog Class).

/// <summary>
/// Gets the folder in Sta Thread
/// </summary>
/// <returns>The path to the selected folder or (if nothing selected) the empty value</returns>
private static string ChooseFolderHelper()
{
    var result = new StringBuilder();
    var thread = new Thread(obj =>
    {
        var builder = (StringBuilder)obj;
        using (var dialog = new FolderBrowserDialog())
        {
            dialog.Description = "Specify the directory";
            dialog.RootFolder = Environment.SpecialFolder.MyComputer;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                builder.Append(dialog.SelectedPath);
            }
         }
     });

     thread.SetApartmentState(ApartmentState.STA);
     thread.Start(result);

     while (thread.IsAlive)
     {
         Thread.Sleep(100);
      }

    return result.ToString();
}
Aditya Korti
  • 692
  • 2
  • 12
  • 28
Jay Riggs
  • 53,046
  • 9
  • 139
  • 151