user6879072 user6879072 - 2 months ago 16
C# Question

How to fix ObjectDisposedException was Unhandled?

So I'm trying to write a simple code for educational purpose that takes a string from a textbox and writes it to txt file. Every time upon pressing the button for the second time I get this error message: Error Message

Here is the code:

StreamWriter sw = new StreamWriter("somefile.txt");
private void button1_Click(object sender, EventArgs e)
{
string textBoxStuff = textBox1.Text;
textBox1.Text = "";
using (sw)
{
sw.WriteLine(textBoxStuff);
}
}

PMV PMV
Answer

Because you are explicitly telling it to close sw after the first time you press the button.

            using (sw)
            {
                sw.WriteLine(textBoxStuff);
            }

At the end of a using() statement, the object being used is disposed. That's all a using statement really is, it's basically syntactic sugar around the following:

            try
            {
                sw.WriteLine(textBoxStuff);
            }
            finally
            {
                sw.Dispose();
            }

In this case, your variable sw stays in scope and is still available for the second button press, but your first button press has already closed the file when Dispose() was called. If you really intend to keep the file open for the life of this form, you don't want to use using here, you want to dispose of the object at a more appropriate point.

The other option is not to hold the file open through the entire lifetime of your form, but open and close it each time you push the button. In that case, you'd make a local streamwriter object and put it in a using statement.

Comments