使用保存文件对话框时出现异常



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

在 Main 方法上添加 STAThreadAttribute 属性。如果程序访问与 OLE 相关的函数(如剪贴板类)是必需的。

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

最新更新