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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With