使用 StreamWriter 写入时 C# 程序崩溃 [英] C# Program crashes when Writing using StreamWriter

查看:67
本文介绍了使用 StreamWriter 写入时 C# 程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mscorlib.dll 中发生类型为System.IO.IOException"的未处理异常

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

它仅在文件已创建时有效.当我删除文件并从头开始时,它会出现以下错误

It works only when the file is already created. When i delete the file and start from scratch it gives the following error

代码:

    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 而不处理流.看看这里.

The error here is inside your Btn_Create_Click. You are using File.CreateText without disposing the stream. Take a look here.

只需调用 Dispose 或将其放在 Using 中.

Just call Dispose or just place it inside a 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");
    }
}

这篇关于使用 StreamWriter 写入时 C# 程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆