附件文件显示为空白

时间:2019-01-14 09:11:29

标签: c# .net email-attachments

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

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

1 个答案:

答案 0 :(得分:2)

因为您已经在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,因为它还会关闭基础流。