我有一些代码可以将附件添加到电子邮件中。我通过类构造函数的Stream
重载添加它们。Attachment
执行此操作的代码如下所示:
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
字节数组在哪里。我想正确处理每个附件和流,但是在发送消息之前我不能这样做,所以我正在考虑将它们添加到 a 中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();
}
}
但是有些事情告诉我,如果仍然有一个参考漂浮在周围,没有得到垃圾收集或其他东西,那么它们就不会正确处理。有什么想法吗?