Do you need to close FileStream AND StreamWriter?

  • Thread starter Thread starter Dan
  • Start date Start date
D

Dan

In the following example, is it necessary to close the FileStream object as
well as the StreamWriter object?

FileStream fs = new FileStream(fileName,
FileMode.CreateNew, FileAccess.Write, FileShare.None);

StreamWriter swFromFile = new StreamWriter(logFile);
swFromFile.Write(textToAdd);
swFromFile.Flush();
swFromFile.Close();
 
Hi

From MSDN:

StreamWriter.Close Method:

Closes the current StreamWriter and the underlying stream.

Cheers,
 
Dan said:
In the following example, is it necessary to close the FileStream object as
well as the StreamWriter object?

FileStream fs = new FileStream(fileName,
FileMode.CreateNew, FileAccess.Write, FileShare.None);

StreamWriter swFromFile = new StreamWriter(logFile);
swFromFile.Write(textToAdd);
swFromFile.Flush();
swFromFile.Close();

I don't believe it's strictly necessary, but personally I think it's a
good idea. I wouldn't close it like the above anyway though - that
fails if an exception is thrown. Use using statements instead:

using (FileStream fs = new FileStream (...))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(textToAdd);
}
}

Note that Close() will call Flush() anyway.
 
Hi Dan,

In your example *no* you don't need to close the writer. As long as you do
flushing the writer you can leave it alone and close the stream or keep
using it with other writers or pass it as a parameter to methods, etc. You
don't have to close the stream. If you had to it will make using writers and
memory streams nearly imposible in most of the cases.


What you have to do though is to flush the writer when you finish using it

So, yes, your example is correct.
 
Stoitcho Goutsev (100) said:
In your example *no* you don't need to close the writer. As long as you do
flushing the writer you can leave it alone and close the stream or keep
using it with other writers or pass it as a parameter to methods, etc. You
don't have to close the stream. If you had to it will make using writers and
memory streams nearly imposible in most of the cases.

Not with using statements, and bearing in mind that MemoryStream has
ToArray which can be used after it's been closed.

You definitely should close at least *one* of the stream or the writer
though.
What you have to do though is to flush the writer when you finish using it

Only if you don't close the writer.
 
Back
Top