views:

324

answers:

2

Hello everyone,

For a .Net MemoryStream object instance, do I need to close it explicitly after using it? Or no need to close it? Which is the best practices?

I am using VSTS2008 + .Net 3.5 + C#.

thanks in advance, George

+2  A: 

you should close it when you are done with it. The best practice is to close the stream in the finally section of a try-catch-finally block. you can get more information here:

http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx

free-dom
Very good answer! Thanks!
George2
+5  A: 

Better yet would be to use Using

using (MemoryStream ms = /*get it using your favorite ctor*/)
{
    // use it here

    // and now flush and copy to a file stream (for example)
    ws.Flush();
    byte[] buffer = ws.ToArray();
    using (Stream stream = new FileStream("fileName", FileMode.Create))
        stream.Write(buffer, 0, buffer.Length);
}

A little reminder - if you plan to write it all into another stream at the end, don't forget to Flush() (And don't leave the toilet seat up).

I use a StreamWriter around the ms, to write text data into the memory, and at the end put it all on disc in one go. (I can also change the example here to this case, if you'd like)

Noam Gal
"write it all into another stream at the end" -- can you show me a sample please? What do you mean "into another stream at the end"?
George2
Why flush for a memory stream? The comment on this method is: "Overrides Flush so that no action is performed."
Simon D
I think I copied the code from my usage of a `MemoryStream` around a `StreamWriter`, and I was flushing the `StreamWriter` instance, to make sure all text written to it gets "inside" the `MemoryStream` before reading the array.I do recall not flushing at first, and got files that did not contain all expected data.
Noam Gal