简体   繁体   中英

Visual studio 2015, C# STAThread not working

STAThread is being ignored in VS 2015? I have my main method with:

[STAThread]
static void Main(string[] args)
{...}

And i have a function which use System.Windows.Forms.OpenFileDialog and gives me the following 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."}

CODE:

 try
            {
                System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog
                {
                    InitialDirectory = @"C:\",
                    Title = "Browse Text Files",

                    CheckFileExists = true,
                    CheckPathExists = true,

                    DefaultExt = "txt",
                    Filter = "txt files (*.txt)|*.txt",
                    FilterIndex = 2,
                    RestoreDirectory = true,

                    ReadOnlyChecked = true,
                    ShowReadOnly = true
                };

                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                }
            }catch(Exception e)
            {

            }

This solved my problem.

You can use OpenFileDialog in MTA using this 2 classes:

https://acharyarajasekhar.wordpress.com/2015/04/10/c-winforms-openfiledialog-with-mtathread/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM