Is it necessary to close StreamWriter?

ilya2

Active member
Joined
Apr 13, 2004
Messages
29
Location
Slovakia
Hi, Im doing some stuff with WebResponse and its response stream. Ive created a wrapper class that copies the stream into its own stream so that it can be able to seek through the stream.

I accomlish that by creating StreamWriter which writes data from the original stream to my stream. However, if I close the StreamWriter at the end, it also closes the underlying stream. Nobody can take that stream and read it then.
So, is it ok to let the StreamWriter open so that the stream also stays open?

Thanks
 
Iceplug said:
Yes. :)
You can set the stream to seek back to the beginning if you need to read the stream again.

Hm, maybe Im missing something, but this code causes an ObjectDisposedException with message Cannot access a closed Stream.

Code:
MemoryStream memoryStream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(memoryStream);
streamWriter.Write("Some data.");
streamWriter.Close();
memoryStream.Seek(0,SeekOrigin.Begin);
 
Closing the StreamWriter will also close its underlying Stream - you will be getting the error when you try to seek on the underlying MemoryStream.
 
Back
Top