StreamWriter to do not write to file

attachment, c#, email, memorystream, streamwriter

Solution

Try rewinding the stream:

writer.Flush();
ms.Position = 0; // <===== here

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);

Otherwise, the stream is still going to be positioned at the end, and reading from there will immediately report EOF.

Problem

I have a method in which I send File as attachment. I use `StreamWriter` and `MemoryStream` to create attachment. Code below: ``` public void ComposeEmail(string from, string to, SmtpClient client) { MailMessage mm = new MailMessage(from, to, "Otrzymałeś nowe zamówienie od "+from , "Przesyłam nowe zamówienie na sprzęt"); mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; // Adding attachment: using (var ms = new System.IO.MemoryStream()) { using (var writer = new System.IO.StreamWriter(ms)) { writer.Write("Hello its my sample file"); writer.Flush(); 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"; mm.Attachments.Add(attach); try { client.Send(mm); } catch (SmtpException e) { Console.WriteLine(e.ToString()); } } } } ``` as You can see in these lines I write to "file": ``` writer.Write("Hello its my sample file"); writer.Flush(); ``` While debugging I can see that `MemoryStream` has length of 24 ( just like length of string written to it). But file received in mailbox is empty. What am I doing wrong?

Original source