Simon Harriyott

FolderBrowseDialog in installer custom actions

Worked round an interesting problem with installer custom actions, where the FolderBrowseDialog displayed the dialog, the buttons and the label, but no directory browse control. The problem turned out to be with threading, as the control is COM, and must run on an STA thread. The installer runs in MTA, so it doesn't work. The way round it is to kick the dialog off in a method running on a new thread, and block until the thread finishes. As well as setting the apartment state explicitly, the STAThread decorator is needed on the method:

private void buttonDir_Click(object sender, EventArgs e)

{

  Thread thread = new Thread(new
    ThreadStart(GetDirectory));

  thread.SetApartmentState(ApartmentState.STA);

  thread.Start();

  thread.Join();

}

[STAThread]
private void GetDirectory()

{

  FolderBrowserDialog folderDlg =
    new
FolderBrowserDialog();

  folderDlg.RootFolder = Environment.SpecialFolder.MyComputer;

  folderDlg.SelectedPath = defaultDirectory;

  folderDlg.ShowNewFolderButton = true;

  if (folderDlg.ShowDialog() == DialogResult.OK)

  {

    selectedPath = folderDlg.SelectedPath;

  }

}
11 December 2006