StreamWriter不写入文件

本文关键字:文件 StreamWriter | 更新日期: 2023-09-27 18:04:05

我有一个方法,其中我发送文件作为附件。我使用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());
                }
            }
        }
    }

你可以看到在这几行中我写到了"file":

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

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

我做错了什么?

StreamWriter不写入文件

尝试倒带:

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。