简体   繁体   中英

StreamWriter to do not write to file

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM