简体   繁体   English

与.Net Mail附件一起使用时,处置MemoryStream

[英]Dispose MemoryStream when using with .Net Mail Attachment

I am using a MemoryStream to add attachments from binary that is stored in a DB. 我正在使用MemoryStream从存储在数据库中的二进制文件中添加附件。 My problem is that I want to properly dispose of the MemoryStream. 我的问题是我想正确处理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. 使用“ using”语句很容易做到这一点,但是当我有多个附件时,我不知道如何正确处理多个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? 有没有很好的方法来遍历和附加文件,但是同时正确处理了我要附加的MemoryStreams? When I tried to flush/close prior to using smtp.Send it through an error stating that the stream was already closed. 当我尝试在使用smtp之前刷新/关闭时,通过错误发送它,指出流已经关闭。

Any suggestions would be appreciated. 任何建议,将不胜感激。

I know this is old post, but it turns out that disposing MailMessage or just enclosing it inside using statement is enough as when MailMessage is disposed all AttachmentCollection is also disposed and when Attachment is disposed, Stream is also disposed. 我知道这是旧的文章,但事实证明,处置MailMessage或只是封闭其内部using的语句是不够的时候MailMessage配置所有AttachmentCollection也被设置,当Attachment被布置, Stream还布置。 Check out ReferenceSource for complete code. 查看ReferenceSource以获得完整的代码。

using(MailMessage mail = new MailMessage())
{
   // Add attachments without worring about disposing them
}

You can iterate the MemoryStream s and dispose them. 您可以迭代MemoryStream并将其处置。 Putting the disposing code in a finally block equals to using statement. 将处置代码放入finally块等于using语句。

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. using语句确保即使在调用对象的方法时发生异常,也将调用Dispose。 You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; 通过将对象放在try块中,然后在finally块中调用Dispose,可以达到相同的结果。 in fact, this is how the using statement is translated by the compiler. 实际上,这就是编译器翻译using语句的方式。

from MSDN MSDN

using (var ms1 = new MemoryStream())
  using (var ms2 = new MemoryStream())
  {
    ...
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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