【发布时间】:2012-10-17 16:28:00
【问题描述】:
我有一些代码可以将附件添加到电子邮件中。我通过Attachment 类构造函数的Stream 重载添加它们。执行此操作的代码如下所示:
List<UploadedDocument> docs = DataBroker.GetUploadedDocs(Convert.ToInt32(HttpContext.Current.Session["offer_id"].ToString()));
//no need to keep this in session
HttpContext.Current.Session["offer_id"] = null;
int counter = 1;
foreach (UploadedDocument doc in docs)
{
stream = new MemoryStream(doc.doc);
attach = new Attachment(stream, "Attachment-" + counter.ToString());
message.Attachments.Add(attach);
}
其中doc.doc 是一个字节数组。我想正确处理每个附件和流,但在发送消息之前我不能这样做,所以我正在考虑将它们添加到 List<Attachment> 和 List<Stream> 然后迭代并调用 dispose.
类似这样的:
List<Attachment> attachments;
List<Stream> streams;
//...
foreach(UploadedDocument doc in docs)
{
stream = new MemoryStream(doc.doc);
streams.Add(stream);
attach = new Attachment(stream,"Name");
attachments.Add(attach);
message.Attachments.Add(attach);
}
//other processing
emailClient.Send(message);
if(attachments != null)
{
foreach(Attachment attachment in attachments)
{
attachment.Dispose();
}
}
if(streams != null)
{
foreach(MemoryStream myStream in streams)
{
myStream.Dispose();
}
}
但是有些东西告诉我,如果仍然有一个参考漂浮在周围,但没有得到垃圾收集或其他东西,那么它就不会正确处理它们。有什么想法吗?
【问题讨论】:
标签: c# email attachment idisposable