When is file.close () required?

I was wondering if Close() should be called in the following situation (if not needed, why?)

 using (var file = System.IO.File.OpenText(myFilePath)) { ... } 

I assume this is necessary in the following situation

 StreamWriter file2 = new System.IO.StreamWriter(myFilePath); newFileContents.ForEach(file2.WriteLine); file2.Close(); 

Is it correct?

Edit:

I thought my question was close () - specific, maybe there was a difference between reading and writing ....

+4
source share
6 answers

With the using construct, you call IDisposable.Dispose automatically at the end of the code block that closes the file. If you are not using the using statement, you should call Close.

With using you also automatically get built-in try / finally exception handling, which will behave more gracefully if something goes wrong once you leave the using block. This other reason using using is a good idea, not its own.

In your case, the using construct is a shorthand for:

 StreamWriter file2 = new System.IO.StreamWriter(myFilePath); try { newFileContents.ForEach(file2.WriteLine); } finally { if (file2!= null) ((IDisposable)file2).Dispose(); } 

If you decompile the StreamWriter Dispose implementation, you will see this call (among others):

 this.stream.Close(); 

in a finally block (if you need absolute proof ;-)

+8
source

OpenText returns a StreamReader , which inherits a TextReader , which inherits the IDisposable interface, which indicates the Dispose() method.

When the using statement goes out of scope, it calls the Dispose () method in the StreamReader implementation of the Dispose () object, which, in turn, closes the stream (i.e. the base file). All this wrapped up in try / finally locked under the covers, which ensures that Dispose () will always be called.

+2
source

the using structure calls the Dispose object when it reaches the end of the script block. This method closes the file.

At any time when you are working with a file, you need to call Dispose or Close so that Windows does not know that the file is free for editing.

0
source

Right.

  • If wrapped in a usage suggestion, file.Close() not required
  • If you did not wrap, you are responsible for Close() and Dispose()
0
source

I was wondering if Close () should be called in the following situation (if not needed, why?)

No, because the using statement removes the object - and therefore removes unmanaged resources.

I assume this is necessary in the following situation

Yes, it will require unmanaged resources to be cleaned up.

0
source

This is not necessary because Dispose() will close the main file. However, since this implementation detail is good practice, I explicitly call Close() when you are done with the stream.

0
source

All Articles