简体   繁体   中英

.Net MemoryStream close issue

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#.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM