2012-09-26 66 views
0

我越來越想使用SaveFileDialog在下列異常時:異常使用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); 
      } 

     } 

回答

2

添加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