问题
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?
回答1:
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);
回答2:
Maybe your tutor is looking for:
File.WriteAllText(saveFileDialog.FileName, textbox.Text);
It's reasonable to prefer concise code, but not at the expense of readability or correctness.
回答3:
Simplest solution without fout.Close() should be:
using (StreamWriter fout = new StreamWriter(saveFileDialog.FileName))
{
fout.Write(textBox.Text);
}
回答4:
If you don't close it, you can't guarantee that it'll write out the last piece of data written to it. This is because it uses a buffer and the buffer is flushed when you close the stream.
Second, it will lock the file as open preventing another process from using it.
The safest way to use a filestream is with a using statement.
回答5:
Short answer, the resources allocated for that operation will not be freed not to mention that it could pottentially lock that file.
回答6:
Consider
using( var fout = new StreamWriter(saveFileDialog.FileName){ fout.write(textBox.Text); }
回答7:
Any how GC will close it for you. But the thing is until the GC closes that stream you are unnecessary putting on hold to the resources
回答8:
You can try with using blok
in order to clean your no managed object
using (var streamWriter = new StreamWriter(saveFileDialog.FileName))
{
streamWriter.Write(textBox.Text);
}
回答9:
It would be a memory hazard.
I would always use StreamWriter in a 'using' statement
using(StreamWriter fout = new StreamWriter(saveFileDialog.FileName)
{
fout.Write(textBox.Text);
}
来源:https://stackoverflow.com/questions/12783947/what-happens-if-streamreader-or-streamwriter-are-not-closed