テキストファイルを作成するためのオプションを調べているときに、説明できないこの動作に出くわしました
どちらのボタンもファイルを作成します
しかし、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);
}
}