0

I've been wondering how can I browse to a directory and save the selected path to a string variable by using an console application? I have tried a few things but none seemed to work. Here's my code:

string path = "";

FolderBrowserDialog fileDialog = new FolderBrowserDialog();
var result = fileDialog.ShowDialog(); //exception

if (result == DialogResult.OK)
{
    path = fileDialog.SelectedPath;
}

Console.WriteLine(path);

It throws ThreadStateException exception at line 3.

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

1 Answers1

4

It seems that you are attempting to use this in a console application which runs in MTA (Multi Threaded Appartment) whereas the FolderBrowserDialog control requires STA (Single Threaded Appartment).

To put your console application in STA try decorating the Main method with the [STAThread] attribute:

class Program
{
    [STAThread]
    static void Main()
    {
        string path = "";
        var fileDialog = new FolderBrowserDialog();
        var result = fileDialog.ShowDialog();

        if (result == DialogResult.OK)
        {
            path = fileDialog.SelectedPath;
        }

        Console.WriteLine(path);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928