附件文件显示空白

attachment files shows blank

这是我的代码,我正在尝试将文本文件作为附件发送而不将其存储到磁盘上...................................... ............

            MailMessage mailMsg = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();

            mailMsg.To.Add("receiver@email.com");
            mailMsg.Subject = "Application Exception";

            MemoryStream MS = new MemoryStream();
            StreamWriter Writer = new StreamWriter(MS);
            Writer.Write(DateTime.Now.ToString() + "hello");
            Writer.Flush();
            Writer.Dispose();

            // Create attachment
            ContentType ct = new ContentType(MediaTypeNames.Text.Plain);
            Attachment attach =new Attachment(MS, ct);
            attach.ContentDisposition.FileName = "Exception Log.txt";

            // Add the attachment
            mailMsg.Attachments.Add(attach);

            // Send Mail via SmtpClient
            mailMsg.Body = "An Exception Has Occured In Your Application- \n";
            mailMsg.IsBodyHtml = true;
            mailMsg.From = new MailAddress("sender@email.com");
            smtpClient.Credentials = new NetworkCredential("sender@email.com", "password");
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.Send(mailMsg);

由于您已在 MemoryStream 中写入,因此该位置位于流的末尾。通过添加将其设置回开头:

MS.Seek(0, SeekOrigin.Begin);

在您完成写入流并刷新编写器之后。所以(部分)你的代码看起来像这样:

...
MemoryStream MS = new MemoryStream();
StreamWriter Writer = new StreamWriter(MS);
Writer.Write(DateTime.Now.ToString() + "hello");
Writer.Flush();
MS.Seek(0, SeekOrigin.Begin);
...

编辑:
您应该避免在编写器上调用 Dispose,因为它还会关闭基础流。