问题
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??
回答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();
}
来源:https://stackoverflow.com/questions/2672576/folder-browse-dialog-not-showing-folders