Dispose MemoryStream when using with .Net Mail Attachment

4.3k Views Asked by At

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.

3

There are 3 best solutions below

2
On BEST ANSWER

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

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

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
}