使用 StreamWriter 写入时 C# 程序崩溃

C# Program crashes when Writing using StreamWriter

'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");
        }
    }
}

}

此处的错误在您的 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");
    }
}