2

I tried to show folderbrowserdialog in wpf but I got this exception

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

I tried to add [STAThread] before this function but no change how can I solve this exception ?

The function is :

private void Save_any_File()
        {
            System.Windows.Forms.FolderBrowserDialog get_location = new System.Windows.Forms.FolderBrowserDialog();
            get_location.ShowDialog();
        }
kartal
  • 17,436
  • 34
  • 100
  • 145

2 Answers2

1

Your Main() function already has the [STAThread] attribute, it is buried in the auto-generated code for WPF. It doesn't have any effect anywhere else but on the Main() method. It ensures that the main thread of the WPF app (aka UI thread) creates a "single-threaded apartment". This is done by the CLR, before any code in your app starts running.

STA is a hard requirement for UI threads, many COM components require it. An STA provides a safe home for software that isn't thread-safe. Thus "single-threaded". The OpenFileDialog is one such component, others are the clipboard and drag+drop support.

And the many, many COM components that try to find a home in your app. In the case of OpenFileDialog, those are the shell extensions that customize the appearance of the folder view.

Long story short, the problem is no doubt that you are trying to display the dialog on a worker thread. No can do. Use Dispatcher.BeginInvoke() to marshal calls to the UI thread.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • where befor ShowDialog() ? or before call the function I will edit my question to add the function can you edit it and add the dispatcher.begininvoeke(); in correct position – kartal Jul 08 '11 at 23:23
  • I don't really want to edit your code, that's not going to solve your problem. You need to understand the answer to get ahead. What part was unclear to you? Have you found the thread yet? – Hans Passant Jul 08 '11 at 23:28
0

This post may be helpful. That's a Windows Forms dialog, you generally need a WindowsFormHost or other interop method.

Community
  • 1
  • 1
sdcoder
  • 496
  • 2
  • 4