C# 在c中按下按钮时获取异常#

C# 在c中按下按钮时获取异常#,c#,winforms,C#,Winforms,我用c#制作了一个按钮,从windows浏览文件和文件夹。下面给出了我的示例代码。问题是:当我单击浏览按钮时,我在下面代码的注释中标记的行中出现以下异常: An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll 我的示例代码: using System; using System.Drawing; using System.Wind

我用c#制作了一个按钮,从windows浏览文件和文件夹。下面给出了我的示例代码。问题是:当我单击浏览按钮时,我在下面代码的注释中标记的行中出现以下异常:

An unhandled exception of type 'System.Threading.ThreadStateException'   occurred in System.Windows.Forms.dll
我的示例代码:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

public class Form1 : Form
{
    public Form1()
    {
        Size = new Size(400, 380);
        Button browse = new Button();
        browse.Parent = this;
        browse.Text = "Browse";
        browse.Location = new Point(220, 52);
        browse.Size = new Size(6 * Font.Height, 2 * Font.Height);
        browse.Click += new EventHandler(ButtonbrowseOnClick);
    }

    public void ButtonbrowseOnClick(object sender, EventArgs e)
    {
         int size = -1;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();  
        DialogResult result = openFileDialog1.ShowDialog();  //getting exception in this line
        if (result == DialogResult.OK) 
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = File.ReadAllText(file);
                size = text.Length;
            }
            catch (IOException)
            {
            }
        }

        Console.WriteLine(size); 
        Console.WriteLine(result);   
    }

    public static void Main()
    {
        Application.Run(new Form1());
    }
}

代码中有什么错误吗?

主方法的顶部使用
[STAThread]
属性应该可以解决问题

[STAThread]          //   <--------Add this
public static void Main()
{
    Application.Run(new Form1());
}

[STAThread]//谢谢。它起作用了。有没有办法打印所选文件的位置@Hossein Narimani RadIs有没有办法打印所选文件的位置@侯赛因·纳里马尼:你已经自己做到了。要获取所选文件的位置,您可以在Windows窗体中使用
openFileDialog1.FileName
@user5379550您可以尝试
MessageBox.Show
@user5379550您可以在窗体类中定义字符串变量(字段或属性),并在第一个方法中将其设置为
FileName
的值,然后在第二个方法中也可以调用它。