创建包含多个条目的Zip文件

时间:2017-03-14 10:50:21

标签: c# .net zip compression

我在创建包含多个条目的zip文件时遇到问题。我看了this类似问题的答案,但仍然没有快乐。我的代码如下:

var folders = await _folderManager.GetDescendentsAsync(id);

using (MemoryStream memoryStream = new MemoryStream())
{
    // Build the archive
    using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        foreach (var folder in folders)
        {
            //get the path 
            var path = GetPath(folder);

            foreach (var file in folder.Documents)
            {
                //get the file stream from storage
                var docStream = _documentManager.DownloadById(file.Id);

                //create an entry in the zip
                ZipArchiveEntry archiveEntry = zipArchive.CreateEntry(path + file.Name);
                using (var entryStream = archiveEntry.Open())
                {
                    await docStream.CopyToAsync(entryStream);
                }
            }
        }

        using (var fileStream = new FileStream(@"C:\Temp\ZipFile.zip", FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            await memoryStream.CopyToAsync(fileStream);
        }
    }
}

我收到包含多个条目的zip文件但是当我尝试打开它时收到错误“意外的归档结束”。

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:0)

CopyToAsync方法以块的形式将一个流的内容复制到另一个流。如果在流的末尾,块大于块大小,则它不会总是被复制到另一个流。要解决此问题,您可以FlushFlushAsync memoryStream

using (var fileStream = new FileStream(@"C:\Temp\ZipFile.zip", FileMode.Create))
{
    memoryStream.Seek(0, SeekOrigin.Begin);
    await memoryStream.CopyToAsync(fileStream);

    await memoryStream.FlushAsync();
}