Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if StreamReader or StreamWriter are not closed?

I'm working on an assignment for a professor that is strict about LOC. For this reason I'd like to do the following:

(new StreamWriter(saveFileDialog.FileName)).Write(textBox.Text);

instead of

StreamWriter sw = new StreamWriter(saveFileDialog.FileName);
sw.Write(textBox.Text);
sw.Close();

In the first example I don't close the stream. Is this ok? Will it cause any security or memory problems?

like image 825
Ivan Li Avatar asked Nov 27 '22 04:11

Ivan Li


1 Answers

You may not get any output, or incomplete output. Closing the writer also flushes it. Rather than manually calling Close at all, I'd use a using statement... but if you're just trying to write text to a file, use a one-shot File.WriteAllText call:

File.WriteAllText(saveFileDialog.FileName, textBox.Text);
like image 83
Jon Skeet Avatar answered Dec 05 '22 09:12

Jon Skeet