如何closures在一个循环内创build多个MemoryStream?

我不能使用内循环,因为那样我就不能发送电子邮件,因为cannot access a closed stream

我不能using(MemoryStream memoryStream = new MemoryStream()){the rest of the codes}因为那么只有第一个Excel会有数据,其余的将是空的,文件大小为64 B.我已经validation所有的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); 

没有必要closures这个内存stream。

你只需要确保你的mailMessage处理正确。 一旦它被处置,所有的附件也被处置,因此它们的Streams

在这里查看MailMessage 源代码并searchDispose()实现:

 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(); } } } 

为了configuration你的mailMessage,只需使用如下这个简单的例子:

 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); } }