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....
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.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With