我使用以下代码将文件附加到电子邮件中.
msg = new MailMessage();
using (strMem = new MemoryStream((byte[])attDr["filedata"]))
{
using (strWriter = new StreamWriter(strMem))
{
strWriter.Flush(); strMem.Position = 0;
using (attachment = new Attachment(strMem, attDr["filename"].ToString()))
{
msg.Attachments.Add(attachment);
}
}
}
...
...
msg.Send(); //Error: System.ObjectDisposedException: Cannot access a closed Stream.
Run Code Online (Sandbox Code Playgroud)
错误消息是://错误:System.ObjectDisposedException:无法访问已关闭的Stream
我猜测"USING"语句在退出块时关闭流.但为什么"Attacments.Add()"没有制作自己的流副本?
Han*_*ant 43
Send()方法将访问附件以将它们嵌入到邮件消息中.这就是kaboom,内存流被处理掉了.你需要移动的内部发送()调用使用的语句,因此流没有得到处置,直到后发送消息.
提到在这里没有必要使用因为内存流没有任何需要处理的非托管资源总是让我陷入麻烦.所以我不会提起这件事.
Lor*_*ill 13
我在处理创建MailMessage的场景时发现的一个解决方案是与发送分开,可能还有多个附件是使用List of MemoryStream对象
// Tuple contains displayName and byte[] content for attachment in this case
List<Tuple<string,byte[]>> attachmentContent;
MailMessage email = BuildNativeEmail(requestObject, out attachmentContent);
List<MemoryStream> streams = new List<MemoryStream>();
foreach(Tuple<string,byte[]> attachment in attachmentContent)
{
MemoryStream m = new MemoryStream(attachment.Item2);
email.Attachments.Add(new System.Net.Mail.Attachment(m, attachment.Item1));
streams.add(m);
}
// client represents a System.Net.Mail.SmtpClient object
client.Send(email);
foreach(MemoryStream stream in streams)
{
stream.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
小智 8
Yes.Its true.Using 语句在退出块时关闭流。
不要使用“使用”语句。发送电子邮件后,为附件调用dispose()方法。
...
...
msg.Send();
msg.Attachments.ToList().ForEach(x => x.ContentStream.Dispose());
Run Code Online (Sandbox Code Playgroud)
您也可以对AlternateView使用相同的方式。
...
...
msg.AlternateViews.Add(alternateView);
...
msg.Send();
...
if (alternateView != null) {
mail.AlternateViews.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13369 次 |
最近记录: |