Is it always necessary to close streams or, because .net is managed code, will it be closed automatically as soon as it drops out of scope (assuming there are no exceptions raised).
Illustrated:
static string SerialiseObjectToBase64(object obj)
{
var mstream = new MemoryStream();
...
return Convert.ToBase64String(mstream.ToArray());
}
Is the above code acceptable?
If you don't close streams, you may have problems opening them back up again. This is especially true if they're hanging off the end of sockets. Closing a stream also makes sure that data is flushed through the stream if there is any data left to send.
You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .
1 Answer. No, there is no need to explicitly call reader. Close if the reading process is inside a using block. By using a using statement (that sounds awkward out loud) everything will be closed and disposed when the code exits the block.
Stream Dispose() also calls Close() if it hasn't already been closed. So your Close() calls are redundant.
With a MemoryStream
it is a bit of a moot point - since you are ultimately talking to a managed byte[]
(so it is still going to wait for routine garbage collection). But in general, yes: you should close (better: Dispose()
via using
, so it gets shut down upon exception) the stream when done, otherwise you might not flush some data to the underlying (unmanaged) destination. And there are some streams that don't actually fully "flush" on Flush()
- they need to be Close()
d (compression streams in particular).
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