在探索创建文本文件的选项时,我偶然发现了这种我无法解释的行为
两个按钮都会创建一个文件
但是当我使用 button1 button2 创建文件时会产生错误。
这仅在实际创建文件时发生。
创建文件后,按钮 1 和 2 按预期运行
一个简单的 GUI 程序的示例代码 2 个按钮和一个包含多行文本框
string logFile;
public Form1()
{
InitializeComponent();
logFile = "test.txt";
}
private void button1_Click(object sender, EventArgs e)
{
if (!System.IO.File.Exists(logFile))
{
System.IO.File.Create(logFile);
textBox1.AppendText("File Created\r\n");
}
else
{
textBox1.AppendText("File Already Exists\r\n");
}
System.IO.File.AppendText("aaa");
}
private void button2_Click(object sender, EventArgs e)
{
// 7 overloads for creation of the Stream Writer
bool appendtofile = true;
System.IO.StreamWriter sw;
try
{
sw = new System.IO.StreamWriter(logFile, appendtofile, System.Text.Encoding.ASCII);
sw.WriteLine("test");
textBox1.AppendText("Added To File Created if Needed\r\n");
sw.Close();
}
catch (Exception ex)
{
textBox1.AppendText("Failed to Create or Add\r\n");
// note this happens if button 1 is pushed creating the file
// before button 2 is pushed
// eventually this appears to resolve itself
textBox1.AppendText("\r\n");
textBox1.AppendText(ex.ToString());
textBox1.AppendText("\r\n");
textBox1.AppendText(ex.Message);
}
}