What happens if StreamReader or StreamWriter are not closed?

亡梦爱人 提交于 2019-12-01 19:45:29

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

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.

Simplest solution without fout.Close() should be:

        using (StreamWriter fout = new StreamWriter(saveFileDialog.FileName))
        {
            fout.Write(textBox.Text);
        }

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.

Short answer, the resources allocated for that operation will not be freed not to mention that it could pottentially lock that file.

Consider

using( var fout = new StreamWriter(saveFileDialog.FileName){ fout.write(textBox.Text); }

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

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);
        }
Antarr Byrd

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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!