【问题标题】:Does CopyTo store the whole thing in memory?CopyTo 是否将整个内容存储在内存中?
【发布时间】:2015-06-04 10:53:14
【问题描述】:

我有以下代码 sn-p,它旨在将文件添加到 .zip 文件中,同时计算它们的 sha1 校验和。

但是,它的大文件内存不足。

它的哪一部分导致整个文件在内存中?当然,这一切都应该只是流式传输?

using (ZipArchive archive = ZipFile.Open(buildFile, ZipArchiveMode.Update))
{
    foreach (var fileName in nameList)
    {
        ZipArchiveEntry entry = archive.CreateEntry(source.filename);
        using (Stream zipData = entry.Open())
        using (SHA1Managed shaForFile = new SHA1Managed())
        using (Stream sourceFileStream = File.OpenRead(fileName))
        using (Stream sourceData = new CryptoStream(sourceFileStream, shaForFile, CryptoStreamMode.Read))
        {
            sourceData.CopyTo(zipData);
            print fileName + ':' + shaForFile.Hash;
        }
    }
}

【问题讨论】:

  • @Yuval no, it isn't.
  • @CodeCaster 分块读取,但最终整个文件都在ZipArchive中。
  • 是的,所以 OP 需要不时将 zip 文件刷新到磁盘。
  • 它不是 CopyTo() 也不是 Sha1Managed,它们使用小缓冲区。问题在于 ZipArchiveMode.Update,它可能需要对磁盘上的文件进行重大更改。当您使用 ZipArchiveMode.Create 时,它​​只能直接流式传输到磁盘。我猜唯一真正的解决方法是首先提取现有内容,以便您可以从头开始创建整个 zip 存档。
  • 谢谢,就是这样。幸运的是,我可以在这里使用创建模式。您愿意将此作为答案,然后我可以接受吗?

标签: c# zip sha1


【解决方案1】:

(从评论中复制 - 因为这回答了问题)

问题在于 ZipArchiveMode.Update,它可能需要对磁盘上的文件进行重大更改。它只能在您使用 ZipArchiveMode.Create 时直接流式传输到磁盘

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 2010-12-29
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多