StreamWriter不写入文件

时间:2014-05-19 08:28:16

标签: c# email attachment streamwriter memorystream

我有一种方法,我将文件作为附件发送。 我使用StreamWriterMemoryStream来创建附件。 代码如下:

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

你可以在这些行中看到我写给“文件”:

writer.Write("Hello its my sample file");
writer.Flush();

调试时我可以看到MemoryStream的长度为24(就像写入字符串的长度一样)。 但邮箱中收到的文件是空的。

我做错了什么?

1 个答案:

答案 0 :(得分:6)

尝试倒回流:

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

否则,流仍将定位在最后,从那里读取将立即报告EOF。