Attaching a File from MemoryStream to a MailMessage in C#
In this article, we'll address the issue of attaching a file from a MemoryStream to a MailMessage in C#.
Issue:
The reader is currently storing files on disk using FileStream and then adding them as attachments using System.Net.Mail.MailMessage.Attachments.Add. However, they wish to avoid storing files on disk and instead work with MemoryStream.
Solution:
To achieve this, we can utilize the following approach:
System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(ms); writer.Write("Hello its my sample file"); writer.Flush(); writer.Dispose(); ms.Position = 0; System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct); attach.ContentDisposition.FileName = "myFile.txt"; // I guess you know how to send email with an attachment // after sending email ms.Close();
Additional Notes:
The above is the detailed content of How to Attach a File from a MemoryStream to a MailMessage in C#?. For more information, please follow other related articles on the PHP Chinese website!