【问题标题】:How to close multi MemoryStream created inside a loop?如何关闭循环内创建的多个 MemoryStream?
【发布时间】:2016-08-19 02:48:32
【问题描述】:

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

【问题讨论】:

  • 释放内存流只会阻止未来的读/写(您想要 - 您希望电子邮件库从流中读取)。处理流不会导致更快地清理内存。据我所知,您的代码是正确的。但是,您可以在创建流时将流添加到列表中,然后根据需要在Send 之后处理每个流。请参阅this 了解更多信息
  • 我不会出汗的。 MemoryStream 实际上并没有任何非托管资源可供处置,因此让 GC 处理它而不关闭或处置它就可以了。请注意,这是 IDisposables 最佳实践的一个例外。
  • MemoryStream 并不是真正的问题,因为如上所述,它没有非托管资源。但是,如果您确实有其他一些流,只需在发送 MailMessage 对象后处理它。它应该处理所有附件及其底层流。

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


【解决方案1】:

没有必要关闭这个内存流。

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

查看MailMessagesource 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2020-08-29
    • 2014-12-08
    • 1970-01-01
    相关资源
    最近更新 更多