Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Do you need to close FileStream AND StreamWriter?

0 views
Skip to first unread message

Dan

unread,
Sep 22, 2004, 8:25:16 AM9/22/04
to
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();


Ignacio Machin ( .NET/ C# MVP )

unread,
Sep 22, 2004, 8:29:34 AM9/22/04
to
Hi

From MSDN:

StreamWriter.Close Method:

Closes the current StreamWriter and the underlying stream.

Cheers,


--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation


"Dan" <d...@dontspamme.com> wrote in message
news:eTyUL7Jo...@TK2MSFTNGP15.phx.gbl...

Jon Skeet [C# MVP]

unread,
Sep 22, 2004, 8:31:33 AM9/22/04
to

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.

--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Stoitcho Goutsev (100) [C# MVP]

unread,
Sep 22, 2004, 9:38:28 AM9/22/04
to
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.

--
HTH
Stoitcho Goutsev (100) [C# MVP]


"Dan" <d...@dontspamme.com> wrote in message
news:eTyUL7Jo...@TK2MSFTNGP15.phx.gbl...

Jon Skeet [C# MVP]

unread,
Sep 22, 2004, 10:45:20 AM9/22/04
to
Stoitcho Goutsev (100) [C# MVP] <1...@100.com> wrote:
> 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.

0 new messages