C# 使用ZipOutputStream归档多个文件会给我一个空的归档文件

C# 使用ZipOutputStream归档多个文件会给我一个空的归档文件,c#,.net,memorystream,sharpziplib,C#,.net,Memorystream,Sharpziplib,我试图下载一堆文件,我正在通过ZipoutStream压缩(归档) using (var zipStream = new ZipOutputStream(outputMemStream)) { foreach (var documentIdString in documentUniqueIdentifiers) { ... var blockBlob = container.GetBlockBlobReference(documentId.T

我试图下载一堆文件,我正在通过ZipoutStream压缩(归档)

using (var zipStream = new ZipOutputStream(outputMemStream))
{
    foreach (var documentIdString in documentUniqueIdentifiers)
    {   
        ...
        var blockBlob = container.GetBlockBlobReference(documentId.ToString());

        var fileMemoryStream = new MemoryStream();

        blockBlob.DownloadToStream(fileMemoryStream);

        zipStream.SetLevel(3); 

        fileMemoryStream.Position = 0;

        ZipEntry newEntry = new ZipEntry(document.FileName);
        newEntry.DateTime = DateTime.Now;

        zipStream.PutNextEntry(newEntry);

        fileMemoryStream.Seek(0, SeekOrigin.Begin);
        StreamUtils.Copy(fileMemoryStream, zipStream, new byte[4096]);

        zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.

    }

    outputMemStream.Seek(0, SeekOrigin.Begin);
    return outputMemStream;
}
在我的控制器中,我返回以下代码,这些代码应该下载我在上一个示例中创建的Zip文件。控制器操作在浏览器中下载文件,但存档文件为空。我可以看到从上面的方法返回的内容长度

file.Seek(0, SeekOrigin.Begin);
return File(file, "application/octet-stream", "Archive.zip");

有人知道为什么我的控制器返回的文件是空的或损坏的吗?

我认为您需要关闭条目和最终的压缩流。您还应该
使用
并处理所有流。试试这个:

using (var zipStream = new ZipOutputStream(outputMemStream))
{
    zipStream.IsStreamOwner = false;
    // Set compression level
    zipStream.SetLevel(3); 

    foreach (var documentIdString in documentUniqueIdentifiers)
    {   
        ...
        var blockBlob = container.GetBlockBlobReference(documentId.ToString());

        using (var fileMemoryStream = new MemoryStream())
        {
            // Populate stream with bytes
            blockBlob.DownloadToStream(fileMemoryStream);

            // Create zip entry and set date
            ZipEntry newEntry = new ZipEntry(document.FileName);
            newEntry.DateTime = DateTime.Now;
            // Put entry RECORD, not actual data
            zipStream.PutNextEntry(newEntry);
            // Copy date to zip RECORD
            StreamUtils.Copy(fileMemoryStream, zipStream, new byte[4096]);
            // Mark this RECORD closed in the zip
            zipStream.CloseEntry();
        }
    }

    // Close the zip stream, parent stays open due to !IsStreamOwner
    zipStream.Close();

    outputMemStream.Seek(0, SeekOrigin.Begin);
    return outputMemStream;
}
编辑-您应该删除:

// Reset position of stream
fileMemoryStream.Position = 0;

很确定这就是问题所在。

所以我更新了代码,但当我从控制器下载时,它仍然会给我一个错误,即代码无效。ie:压缩(压缩)文件夹“…”无效。@jimfromthegym JimMackin它有大小吗?还是0字节?@jimfromthegym JimMackin实际上不会重置流的位置。请参阅更新的代码。我将位置重置为0,但它仍然不起作用。让我们继续。