Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 801
scarpacci Avatar asked Jan 24 '12 06:01

scarpacci


2 Answers

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
}
like image 134
Adil Mammadov Avatar answered Sep 30 '22 16:09

Adil Mammadov


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

like image 28
gdoron is supporting Monica Avatar answered Sep 30 '22 16:09

gdoron is supporting Monica