简体   繁体   中英

Dispose MemoryStream when using with .Net Mail Attachment

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.

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
}

You can iterate the MemoryStream s 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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