使用StreamWriter写入时,C#程序崩溃
mscorlib.dll中出现未处理的“System.IO.IOException”类型exception
它仅在文件已创建时有效。 当我删除文件并从头开始时,它会出现以下错误
码:
private void Btn_Create_Click(object sender, EventArgs e) { string path = Environment.CurrentDirectory + "/"+ "File.txt"; if (!File.Exists(path)) { File.CreateText(path); MessageBox.Show("File Created Successfully"); } else { MessageBox.Show("File Already Created"); } } private void Btn_Write_Click(object sender, EventArgs e) { using (StreamWriter sw = new StreamWriter("File.txt")) { sw.WriteLine("Hello World"); } } private void Btn_Read_Click(object sender, EventArgs e) { using (StreamReader sr = new StreamReader("File.txt")) { string text = sr.ReadLine(); Text_Show.Text = text; } } private void Btn_Delete_Click(object sender, EventArgs e) { if(File.Exists("File.txt")) { File.Delete("File.txt"); MessageBox.Show("File Deleted"); } } }
}
这里的错误在你的Btn_Create_Click
里面。 您正在使用File.CreateText
而不处理流。 看看这里 。
只需调用Dispose
或将其放在Using
。
像这样:
private void Btn_Create_Click(object sender, EventArgs e) { string path = Environment.CurrentDirectory + "/"+ "File.txt"; if (!File.Exists(path)) { File.CreateText(path).Dispose(); MessageBox.Show("File Created Successfully"); } else { MessageBox.Show("File Already Created"); } }