尝试使用SaveFileDialog时,我收到以下异常:
System.Threading.ThreadStateException: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process
以下是我尝试的代码:
private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog { InitialDirectory = @"C:\", Title = "Save text Files", CheckFileExists = true, CheckPathExists = true, DefaultExt = "txt", Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*", FilterIndex = 2, RestoreDirectory = true };
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
String filePath = saveFileDialog1.FileName;
gridView1.Export(DevExpress.XtraPrinting.ExportTarget.Text, filePath);
}
}
答案 0 :(得分:2)
在Main方法上添加STAThreadAttribute属性。如果您的程序访问OLE相关函数(如Clipboard类,则需要此属性。
)C#
[STAThread]
static void Main(string[] args)
{
}
Visual Basic
<STAThread()> _
Shared Sub Main(args As String())
End Sub
将线程标记为STA(单线程单元)。谷歌应该提供充足的例子。如果您的代码在方法中,则可以使用STAThread属性将方法标记为STA。如果要从匿名委托创建新线程,则可以使用SetApartmentState函数将该线程设置为STA。请注意,如果您正在使用线程,则必须在线程启动之前设置单元状态。
http://www.codeproject.com/Questions/44168/Thread-apartment-modes-and-the-OpenFileDialog