我正在尝试使用C#发送带附件的电子邮件。这是我的方法:
public void SendEmail(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:
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("Hello its my sample file");
writer.Flush();
writer.Dispose();
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());
}
ms.Close();
}
stacktrace指向这一行:
client.Send(mm);
问题是由这一行引起的:
writer.Dispose();
为什么我在使用它写入MemoryStream
之后无法立即处理此元素?
以后不会在代码中使用此元素。
答案 0 :(得分:4)
在编写器上调用Dispose也会释放底层流。发送电子邮件后,您必须同时处理编写者和流。您可以通过将代码包装在两个using语句中来实现这一目的。
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());
}
}
}
答案 1 :(得分:1)
使用阻止,如评论中所建议的那样:
//...
using(System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
using(System.IO.StreamWriter 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);
client.Send(mm);
}
}
答案 2 :(得分:1)
当client.Send
尝试发送时,显然会显示Attachment
,其中MemoryStream
指向已被StreamWriter
关闭的ms.CanRead
。您可以通过检查writer.Dispose()
来验证这一点。它将返回false。
访问已关闭的流会抛出异常,这就是您所遇到的情况。解决它只是摆脱MemoryStream
,因为没有任何东西可以用{{1}}处理或在你完成工作后处理它。