C# Program crashes when Writing using StreamWriter

纵然是瞬间 提交于 2019-12-20 07:15:37

问题


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

Code:

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

}


回答1:


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

Just call Dispose or just place it inside a Using.

Like so:

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


来源:https://stackoverflow.com/questions/43687909/c-sharp-program-crashes-when-writing-using-streamwriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!