StreamWriter不写入文件

szp*_*pic 3 c# email memorystream attachment streamwriter

我有一个方法,我发送文件作为附件.我使用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());
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

正如你可以在这些行中看到我写的"文件":

writer.Write("Hello its my sample file");
writer.Flush();
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

Mar*_*ell 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);
Run Code Online (Sandbox Code Playgroud)

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

  • @szpic放在一边:这里的经典类比是"录像带"或"录音带"; 问题是,新一代开发人员现在正在出现,既没有看到也没有使用视频"磁带"或音频"磁带"; p (2认同)