我使用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());
}
}
代码中有什么问题吗?
答案 0 :(得分:1)
在[STAThread]
方法的顶部使用Main
属性,可以解决问题。
[STAThread] // <--------Add this
public static void Main()
{
Application.Run(new Form1());
}