Please looking in the below codes:
new StreamWriter("c:/myText.txt").Write("Some thing...");
And,
using (var streamWriter = new StreamWriter("c:/myText.txt")
{
streamWriter.Write("Some thing...");
}
The first code creating the file but doesn’t write “Some thing…” in that.
But the second code works as well and write in that.
Why this issue happens? What is the difference?
The
StreamWriterclass implementsIDisposablewhich means that it holds a resource that need to be released or it has some clean up code that needs to be run before the object is garbage collected.In this case calling
Disposecloses the stream, potentially writing the last data to the stream before doing so.By coding
new StreamWriter("c:/myText.txt").Write("Some thing...");you don’t retain a reference to the stream and therefore have no way to callDisposeto properly close the stream.Remember, the Garbage Collector never calls dispose for you. You must explicitly do so.
The second block of code uses the
usingstatement which will automatically callDisposewhen the block is exited. This is the correct way to write this code.