I was recently looking at a piece of code that was attaching a file to an email using System.Net.Mail.Attachment. The current implementation was storing the attachment as a file to a storage device and giving it a unique name. This file then was appended to the MailMessage as follows:
Attachment data = new Attachment(filename);
message.Attachments.Add(data);
Email was then sent and the file was then deleted from the storage device.
Wouldn’t it be faster/better for the file to just be stored in a MemoryStream (which it already is) and then just pass that as the attachment to the Email? I would imagine somewhere in the MailMessage class the file is being read into a stream and sent in the very same manner, and the whole process of storing it to disk is completely unnecessary.
My gut… Writing to disk is completely unnessarry and using the stream should be implemented. (am i wrong?)
Yes, it would be better to avoid writing it to disk, unless that step is necessary for some other reason. The
Attachmentclass can take a stream and a file name as arguments to its constructor, rather than giving it a physical file path.http://msdn.microsoft.com/en-us/library/6sdktyws.aspx