检查运行对话框的线程是否在 STAThread 上。因此,例如确保您的 Main 方法标有 [STAThread] 属性:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
否则,您可以执行此操作(来自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();
}