.Net MemoryStream关闭问题

发布于 2024-08-02 08:12:53 字数 101 浏览 6 评论 0原文

对于.Net MemoryStream对象实例,使用后是否需要显式关闭它?或者说不需要关闭?哪些是最佳实践?

我使用的是 VSTS2008 + .Net 3.5 + C#。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱要勇敢去追 2024-08-09 08:12:53

更好的是使用 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);
}

一点提醒 - 如果您打算最后将其全部写入另一个流中,请不要忘记 Flush() (并且不要不要把马桶座圈打开)。

我在毫秒左右使用 StreamWriter,将文本数据写入内存,最后将其全部写入光盘。 (如果您愿意,我也可以将此处的示例更改为这种情况)

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)

舂唻埖巳落 2024-08-09 08:12:53

完成后应该将其关闭。最佳实践是在 try-catch-finally 块的 finally 部分关闭流。您可以在此处获取更多信息:

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文