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

时间:2016-08-19 02:48:32

标签: c# excel memorystream npoi system.net.mail

我无法在循环中使用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);

1 个答案:

答案 0 :(得分:2)

无需关闭此内存流。

您只需要确保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);
    }
}