Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is file.close() necessary? [duplicate]

Tags:

c#

file-io

I was wondering if it necessary to call Close() in the following situation (if not necessary, why?)

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

I presume it 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 is close() - specific, might have been the difference between reading and writing....

like image 414
Yulia V Avatar asked Feb 27 '13 19:02

Yulia V


2 Answers

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

When the using statement goes out of scope, it calls the Dispose() method on the StreamReader's implementation of Dispose(), which in turn closes the stream (i.e. the underlying file) The whole thing is wrapped in a try/finally block under the covers, which guarantees that Dispose() will always be called.

like image 42
Robert Harvey Avatar answered Sep 27 '22 20:09

Robert Harvey


With the using construct you get IDisposable.Dispose called automatically at the end of the code block which will close the file. If you don't use the using statement you have to call Close yourself.

With using you also automatically get built-in try/finally exception handling which will behave more gracefully if something goes wrong before you exit your using block. That's another reason using using is a good idea instead of rolling your own.

In your case the using construct is shorthand for:

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

If you decompile StreamWriter's implementation of Dispose you will see this call (among others):

this.stream.Close();

in the finally block (If you need absolute proof ;-)

like image 138
Paul Sasik Avatar answered Sep 27 '22 21:09

Paul Sasik