【问题标题】:Routine to zip multiple files in-memory produces corrupt zip files在内存中压缩多个文件的例程会产生损坏的 zip 文件
【发布时间】:2015-08-19 20:06:40
【问题描述】:

以下例程来自 Web API 中的文件服务类。该例程的目的是接收文件路径列表并将 zip 文件作为字节数组返回。 (调用此例程的例程将处理将文件传递给用户。)此例程使用来自System.IO.CompressionZipArchive 类。

此例程生成的文件已损坏。返回值的大小始终为 1024 字节。

此代码与我在 MSDN 和 Stack Overflow 上找到的示例几乎相同。它有什么不正确的?

public byte[] RetrieveMultipleFilesAsZip(IEnumerable<string> relativePaths)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            foreach (var path in relativePaths)
            {
                try
                {
                    // ActualPath(): Get the actual path where the file actually lives.
                    var actualPath = ActualPath(path);
                    var filename = Path.GetFileName(actualPath);
                    if (filename == null) continue;

                    var archiveEntry = archive.CreateEntry(filename);
                    using (var writer = new StreamWriter(archiveEntry.Open()))
                    {
                        // RetrieveFile(): A routine in this class that gets the contents of each file.
                        writer.Write(RetrieveFile(path));
                    }
                }
                catch (Exception ex)
                {
                    // ignore this
                }
            }

        }

        memoryStream.Seek(0, SeekOrigin.Begin);
        return memoryStream.GetBuffer();
    }
}

【问题讨论】:

  • 跟踪代码,似乎只有文件的条目被写入流,而不是文件的内容。给定 6 个不同大小的文件,using archive 块内只写入了大约 350 个字节。在退出 using archive 块时,又写入了 400 个字节。

标签: .net zip


【解决方案1】:

StreamWriter改为BinaryWriter,并设置archive.CreateEntry()compressionLevel参数。

【讨论】:

  • 现在我得到一个大小合适的 Zip 文件,但 Windows 说它无效。由于该例程应该将文件以byte[] 的形式返回给调用者,因此将该文件发送给用户的例程可能会搞砸。
  • 似乎我的一个测试文件已损坏,或导致存档损坏。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多