.Net MemoryStream close issue

点点圈 提交于 2020-01-03 02:00:34

问题


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


回答1:


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




回答2:


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)



来源:https://stackoverflow.com/questions/1326026/net-memorystream-close-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!