我不能在循环中使用using,因为这样我就不能发送电子邮件了,因为cannot access a closed stream。
我不能using(MemoryStream memoryStream = new MemoryStream()){the rest of the codes},因为只有第一个excel将有数据,其余的将是空的文件大小为64B。我已经验证了所有excel有数据,然后通过电子邮件发送它。
foreach (workbook excel in workbooks)
{
MemoryStream memoryStream = new MemoryStream();
excel.hssfWorkBook.Write(memoryStream);
memoryStream.Position = 0;
mailMessage.Attachments.Add(new Attachment(memoryStream, excel.fileName, "application/vnd.ms-excel"));
}
smtpClient.Send(mailMessage);发布于 2016-08-19 10:55:27
不需要关闭这个内存流。
你只需要确保你的mailMessage被正确的放置。一旦它被释放,所有附件也被释放,因此它们的Streams也被释放。
查看MailMessage source code here和search Dispose()的实现:
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true;
if(views != null){
views.Dispose();
}
if(attachments != null){
attachments.Dispose();
}
if(bodyView != null){
bodyView.Dispose();
}
}
}要处理您的mailMessage,只需像这个简单的例子一样使用using:
using (var mailMessage = new MailMessage())
{
using (var smtpClient = new SmtpClient())
{
foreach (workbook excel in workbooks)
{
MemoryStream memoryStream = new MemoryStream();
excel.hssfWorkBook.Write(memoryStream);
memoryStream.Position = 0;
mailMessage.Attachments.Add(new Attachment(memoryStream, excel.fileName, "application/vnd.ms-excel"));
}
smtpClient.Send(mailMessage);
}
}https://stackoverflow.com/questions/39030377
复制相似问题