Search code examples
c#streamwriter

C# Program crashes when Writing using StreamWriter


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

}


Solution

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