gpt4 book ai didi

c# - 发送附件时无法访问已关闭的流

转载 作者:太空宇宙 更新时间:2023-11-03 19:08:21 26 4
gpt4 key购买 nike

我正在尝试使用 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();
}

堆栈跟踪指向这一行:

client.Send(mm);

问题是由这一行引起的:

writer.Dispose();

为什么我不能在使用它写入MemoryStream后立即处理这个元素?此元素以后不会在代码中使用。

最佳答案

在编写器上调用 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());
}
}
}

关于c# - 发送附件时无法访问已关闭的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23732587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com