Dispose of MemoryStream when Using with .Net Mail Attachment

I use MemoryStream to add attachments from a binary file that is stored in the database. My problem is that I want to get rid of MemoryStream correctly. This is easy to do with the β€œusing” statement, but when I have several applications, I don’t know how to properly manage multiple MemoryStreams.

Is there a good way to iterate and attach files, but at the same time properly dispose of the MemoryStreams that I use to attach? When I tried to reset / close before using smtp. Send it with an error indicating that the thread is already closed.

Any suggestions would be appreciated.

+4
source share
3 answers

You can iterate through a MemoryStream and destroy them. Entering the recycling code in the finally block is 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 when you call methods on the object. You can achieve the same result by placing the object inside the try block and then calling Dispose on the finally block; in fact, this is how the using statement is translated by the compiler.

from MSDN

+3
source

I know this is an old post, but it turns out that disposing of MailMessage or just turning it on inside the using statement is enough, as when placing MailMessage all AttachmentCollection also deleted, and when the Attachment is located, Stream also located. Run the ReferenceSource for the full code.

 using(MailMessage mail = new MailMessage()) { // Add attachments without worring about disposing them } 
+1
source
 using (var ms1 = new MemoryStream()) using (var ms2 = new MemoryStream()) { ... } 
0
source

Source: https://habr.com/ru/post/1392620/


All Articles