'Getting STA error when try to open OpenFileDialog box in Excel addin project

I have created Excel addin project using Visual Studio to insert a data into database.

The problem is I'm unable to open a File upload box in this.

I am getting an error.

My code:

 [ObsoleteAttribute()]
        [STAThread]
        private void Save(ProgressBarForm pBar)
        {
  OpenFileDialog openFileDialog1 = new OpenFileDialog();
                        DialogResult result =  openFileDialog1.ShowDialog();
                        if (result == DialogResult.OK)
                        {
//execute code

I tried to give attribute to Save method also then also it is giving me the error below:

enter image description here



Solution 1:[1]

You need to put the [STAThread] on your Main method, like so:

[STAThread]
static void Main()
{

Alternatively, start a new thread for saving, along these lines:

var thread = new Thread(mySaveMethod);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew Watson