C# 附件文件显示为空白
这是我的代码,我正在尝试将文本文件作为附件发送,而不将其存储在磁盘上C# 附件文件显示为空白,c#,.net,email-attachments,C#,.net,Email Attachments,这是我的代码,我正在尝试将文本文件作为附件发送,而不将其存储在磁盘上 MailMessage mailMsg = new MailMessage(); SmtpClient smtpClient = new SmtpClient(); mailMsg.To.Add("receiver@email.com"); mailMsg.Subject = "Application Exception";
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);
在您完成对流的写入并刷新writer之后。因此(部分)您的代码如下所示:
...
MemoryStream MS = new MemoryStream();
StreamWriter Writer = new StreamWriter(MS);
Writer.Write(DateTime.Now.ToString() + "hello");
Writer.Flush();
MS.Seek(0, SeekOrigin.Begin);
...
编辑:您应该避免在writer上调用
Dispose
,因为它也会关闭底层流。您的意思是在writer.flush()之前吗@rickvdboschNo.it给出了一个错误:无法访问封闭流。好的。如果我删除2行Writer.Flush(),它就会工作;Writer.Dispose()代码>