Dispose MemoryStream when using with .Net Mail Attachment

这一生的挚爱 提交于 2019-12-23 10:16:12

问题


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.


回答1:


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




回答2:


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. Check out ReferenceSource for complete code.

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



回答3:


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


来源:https://stackoverflow.com/questions/8982901/dispose-memorystream-when-using-with-net-mail-attachment

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