Ads Inside Post

Search in This Blog

File open Dialogbox show error System Threading ThreadStateException

Problem:

I am wondering when you get the error 'System.Threading.ThreadStateException' while using OpenFileDialog in C# Winform application. So how to solve this?

First we see the error details, after that I will show you solution.
See the screenshot below.
System.Threading.ThreadStateException



















Error is:
"An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll
Additional information: 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."

Code is:

System.Windows.Forms.OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Select HTML/HTML5 file";
openFileDialog.InitialDirectory = "C:";
openFileDialog.Filter = "HTML files (*.html)|*.html|Flv files (*.htm)|*.htm";
openFileDialog.AutoUpgradeEnabled = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
String Chosen_File = openFileDialog.FileName;
       String inputExt = (Path.GetExtension(Chosen_File).ToLower());
       textBox1.Text = Chosen_File;
       textBox2.Text = Chosen_File + "_New" + inputExt;
}
It will show error on the line

if (openFileDialog.ShowDialog() == DialogResult.OK)


The full error code is:
=============================
System.Threading.ThreadStateException was unhandled
  HResult=-2146233056
  Message=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.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner)
       at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.CommonDialog.ShowDialog()
       at CoreRenderer.Form1.button3_Click(Object sender, EventArgs e) in d:\CurrentProject\WinForm\VS2013Testing\CS\CoreRenderer\CoreRenderer\Form1.cs:line 121
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at CoreRenderer.Program.Main() in d:\CurrentProject\WinForm\VS2013Testing\CS\CoreRenderer\CoreRenderer\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
=============================

Solution:

To overcome this problem you need to use Thread class. See below code that how to fix this error.

Example:

Create a method as below:
public void getfile() {
      System.Windows.Forms.OpenFileDialog openFileDialogAvi = new OpenFileDialog();
      openFileDialogAvi.Title = "Select HTML/HTML5 file";
      openFileDialogAvi.InitialDirectory = "C:";
      openFileDialogAvi.Filter = "HTML files (*.html)|*.html|Flv files (*.htm)|*.htm";
      openFileDialogAvi.AutoUpgradeEnabled = true;
      if (openFileDialogAvi.ShowDialog() == DialogResult.OK)
      {
         String Chosen_File = openFileDialogAvi.FileName;
         String inputExt = (Path.GetExtension(Chosen_File).ToLower());
         Invoke((MethodInvoker)delegate
         {
               textBox1.Text = Chosen_File;
               textBox2.Text = Chosen_File + "_New" + inputExt;
         });
      }
   }


On click button access the above method:

private void button2_Click(object sender, EventArgs e) {
       Thread threadGetFile = new Thread(new ThreadStart(getfile));
       threadGetFile.ApartmentState = ApartmentState.STA;
       threadGetFile.Start();         
}