C# folderBrowserDialog STA exception

  • Thread starter Thread starter JEstevao
  • Start date Start date
J

JEstevao

Guest
Hello,

After seeing and reading lots of questions and solution, I wasn't able to overcome the issue I'm having. So, first things first:

FACTS:

  1. I'm using a backgroundWorker to deal with UI update while processing data
  2. In the middle of the process the user is asked if it wants to use a suggested file path or choose one, and in case chooses to select a specific path I open a folderBrowserDialog
  3. The following exception occurs

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.'


WHAT HAVE I TESTED:

The first code I had was:

private void Process_IOT_Documents(object sender, EventArgs e)
{
(...)
while (excelLocation_folderBrowserDialog.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Must choose the location folder where the excel will be created", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

excelFilePath = excelLocation_folderBrowserDialog.SelectedPath;

(...)
}




Since I dealt with handling UI problems before I thought of using the same "Delegate" recipe. So I defined a Delegate and created a function to be called by it:

private string DialogPopUp ()
{
while (excelLocation_folderBrowserDialog.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Must choose the location folder where excel will be created", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

return excelLocation_folderBrowserDialog.SelectedPath;
}

delegate string PopUpDialog();


And then I called the delegate:

private void Process_Documents(object sender, EventArgs e)
{
(...)

PopUpDialog popup = new PopUpDialog(DialogPopUp);

(...)

excelFilePath = popup.Invoke();

(...)
}


And the exception occurred again. I read about BeginInvokes, Threads, etc, but couldn't implement. The thing is


- Why the delegate is not working? After all I'm using in the same piece of code to update the UI. So shouldn't work when open a folderBrowserDialog?


I'm a little lost because I changed all the program when I decided that I needed to update the UI while the backgroundworker was processing all the information. Can anyone help?


Thanks in advance.

Continue reading...
 
Back
Top