Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 附件文件显示为空白_C#_.net_Email Attachments - Fatal编程技术网

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