未处理的类型' System.IO.IOException'发生在mscorlib.dll
仅在已创建文件时才有效。当我删除文件并从头开始时,它会出现以下错误
代码:
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");
}
}
}
}
答案 0 :(得分:0)
此处的错误位于Btn_Create_Click
内。您正在使用File.CreateText
而不处理流。看看here。
只需致电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");
}
}