Take the 2-minute tour ×

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

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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:


share|improve this answer
Very good answer! Thanks! –  George2 Aug 25 '09 at 4:45
add comment

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)
    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)

share|improve this answer
"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 Aug 25 '09 at 4:38
Why flush for a memory stream? The comment on this method is: "Overrides Flush so that no action is performed." –  Simon D Jan 22 '10 at 12:18
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 Jan 24 '10 at 14:49
add comment

Your Answer


