Visual studio 2015, C# STAThread not working



STAThread在VS 2015中被忽略?我有我的主要方法:

[STAThread]
static void Main(string[] args)
{...}

我有一个使用System.Windows.Forms.OpenFileDialog的函数,它给了我以下异常:

{"在进行OLE调用之前,必须将当前线程设置为单线程单元(STA(模式。请确保Main函数上标记了STAThreadAttribute。只有当调试器附加到进程时才会引发此异常

代码:

try
{
System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog
{
InitialDirectory = @"C:",
Title = "Browse Text Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "txt",
Filter = "txt files (*.txt)|*.txt",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
}catch(Exception e)
{
}

这解决了我的问题。

您可以使用以下两个类在MTA中使用OpenFileDialog:

https://acharyarajasekhar.wordpress.com/2015/04/10/c-winforms-openfiledialog-with-mtathread/

最新更新