当与.net邮件附件使用废弃的MemoryStream [英] Dispose MemoryStream when using with .Net Mail Attachment

查看:308
本文介绍了当与.net邮件附件使用废弃的MemoryStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个MemoryStream从存储在一个数据库二进制添加附件。我的问题是,我想正确的方法处理的MemoryStream的。这是很容易做到使用使用的声明,但是当我有多个附件,我不知道如何正确地处理多个MemoryStreams的。

有没有遍历和附加文件的好方法,但还没有在同一时间妥善处置,我使用附上MemoryStreams的?当我试图刷新/关闭之前,使用smtp.Send它通过一个错误,指出流已经关闭。

任何建议将是AP preciated。

解决方案

您可以遍历的MemoryStream 和处置。使用语句把处理code在最后块等于

  VAR列表=新的名单,其中,MemoryStream的>(){新的MemoryStream(),新的MemoryStream()};

尝试
{
    // ....
}
最后
{
    的foreach(VAR的X名单)
    {
        x.Dispose();
    }
}
 

  

using语句确保调用Dispose即使   而您呼叫的对象上的方法发生异常。您可以   通过将对象一试块内实现相同的结果,并   然后调用Dispose在finally块;其实,这是怎样的   using语句是由编译器翻译。

MSDN

I am using a MemoryStream to add attachments from binary that is stored in a DB. My problem is that I want to properly dispose of the MemoryStream. This is easily done using a "using" statement, but when I have more than one attachment I don't know how to properly dispose of the multiple MemoryStreams.

Is there a good way to iterate over and attach the files, but yet at the same time properly dispose of the MemoryStreams that I am using to attach? When I tried to flush/close prior to using smtp.Send it through an error stating that the stream was already closed.

Any suggestions would be appreciated.

解决方案

You can iterate the MemoryStreams and dispose them. Putting the disposing code in a finally block equals to using statement.

var list = new List<MemoryStream>(){new MemoryStream(), new MemoryStream()};

try
{
    //....
}
finally
{
    foreach (var x in list)
    {
        x.Dispose();
    }
}

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

from MSDN

这篇关于当与.net邮件附件使用废弃的MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆