Converting a StringBuilder into attachment to send on email without saving to disk

Needed to take the information in a StringBuilder and convert it into a file to attach to an email - without saving it to the file system! Luckily System.Net.Mail.Attachment has a constructor that allows a MemoryStream to be passed in. You can also pass in the name that you want to be given to the file.
Attachment attachment = null;
StringBuilder csv = new StringBuilder();

csv.Append("something");

attachment = new Attachment(new MemoryStream(Encoding.ASCII.GetBytes(csv.ToString())), "failures." + _resultAttachmentFileExtension);

0 comments: