0

尝试使用 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);
            } 

        }
4

1 回答 1

2

Add the STAThreadAttribute attribute on the Main method. This attribute is required if your program access OLE related functions, like Clipboard class does.

C#

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

Visual Basic

<STAThread()> _
Shared Sub Main(args As String())

End Sub

Mark the thread as a STA (single threaded apartment). Google should provide ample examples. If your code is in a method, you can use the STAThread attribute to mark the method as a STA. If you are creating a new thread from an anonymous delegate, you can use the SetApartmentState function to make the thread an STA. Note that setting the apartment state must be done before the thread is started, if you are using a thread.

http://www.codeproject.com/Questions/44168/Thread-apartment-modes-and-the-OpenFileDialog

于 2012-09-26T01:45:16.520 回答