What happens if StreamReader or StreamWriter are not closed?

I am working on a task for a professor who strictly adheres to LOC . For this reason, I would like to do the following:

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

instead

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

In the first example, I do not close the stream. This is normal? Due to security or memory issues?

+4
source share
9 answers

You cannot get any output or incomplete output. Closing a writer also resets him. Instead of manually calling Close at all, I would use the using statement ... but if you're just trying to write text to a file, use the one-time File.WriteAllText call:

 File.WriteAllText(saveFileDialog.FileName, textBox.Text); 
+15
source

Your tutor may be looking for:

 File.WriteAllText(saveFileDialog.FileName, textbox.Text); 

It is reasonable to prefer compressed code, but not at the expense of readability or correctness.

+8
source

The simplest solution without fout.Close () should be:

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

If you do not close it, you cannot guarantee that it will write out the last piece of data written to it. This is because it uses a buffer, and the buffer closes when the stream closes.

Secondly, it will lock the file as open, preventing another process from using it.

The safest way to use a filter is to use an instruction.

+3
source

The short answer is that the resources allocated for this operation will not be released, not to mention the fact that it can lock this file.

+1
source

Consider

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

How GC will close it for you. But the point is, until the GC closes this thread, which you do not need to put aside for resources

0
source

You can try with using blok for clean your no managed object

  using (var streamWriter = new StreamWriter(saveFileDialog.FileName)) { streamWriter.Write(textBox.Text); } 
0
source

It will be dangerous for memory.

I would always use StreamWriter in the 'using' statement

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

Source: https://habr.com/ru/post/1438430/


All Articles