如何关闭在循环内创建的多个 MemoryStream?

How to close multi MemoryStream created inside a loop?

我不能在循环中使用 using 因为那样我将无法发送电子邮件,因为 cannot access a closed stream.

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

不需要关闭这个内存流。

您只需要确保您的 mailMessage 得到妥善处理。一旦它被处理掉,所有附件也会被处理掉,因此它们的 Streams.

查看 MailMessage source code here 并搜索 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);
    }
}