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