【问题标题】:Create in memory zip from a file从文件中创建内存 zip
【发布时间】:2016-09-23 08:21:49
【问题描述】:

DeflateStream 是否应该创建可以存储为标准 .zip 存档的存档流?

我正在尝试从本地文件创建内存 zip(远程发送)。 我使用 DeflateStream 从本地磁盘上的文件中获取压缩字节数组:

public static byte[] ZipFile(string csvFullPath)
    {
        using (FileStream csvStream = File.Open(csvFullPath, FileMode.Open, FileAccess.Read))
        {
            using (MemoryStream compressStream = new MemoryStream())
            {
                using (DeflateStream deflateStream = new DeflateStream(compressStream, CompressionLevel.Optimal))
                {
                    csvStream.CopyTo(deflateStream);
                    deflateStream.Close();
                    return compressStream.ToArray();
                }
            }
        }
    }

这很好用。 但是,当我将生成的字节转储到 zip 文件时:

byte[] zippedBytes = ZipFile(FileName);
File.WriteAllBytes("Sample.zip", zippedBytes);

我无法使用 Windows 内置 .zip 功能(或任何其他第 3 方存档工具)打开生成的 .zip 存档。

我现在计划的另一种方法是使用 ZipArchive - 但是这需要在磁盘上创建临时文件(首先将文件复制到单独的目录中,然后对其进行压缩,然后将其读入字节数组,然后将其删除)

【问题讨论】:

  • 你应该使用ZipArchive类。它适用于流,不需要临时文件。

标签: c# .net zip deflate deflatestream


【解决方案1】:

你可以使用这个不错的库https://dotnetzip.codeplex.com/

或者您可以使用 ZipArchive,它与 MemoryStream 配合得非常好:

public static byte[] ZipFile(string csvFullPath)
{
    using (FileStream csvStream = File.Open(csvFullPath, FileMode.Open, FileAccess.Read))
    {
        using (MemoryStream zipToCreate = new MemoryStream())
        {
            using (ZipArchive archive = new ZipArchive(zipToCreate, ZipArchiveMode.Create, true))
            {
                ZipArchiveEntry fileEntry = archive.CreateEntry(Path.GetFileName(csvFullPath));
                using (var entryStream = fileEntry.Open())
                {
                    csvStream.CopyTo(entryStream);
                }
            }

            return zipToCreate.ToArray();
        }
    }
}

【讨论】:

  • 代码工作正常,但如果我将字节转储到 .zip 文件中,则无法打开它(据称存档损坏)。顺便提一句。该文件的二进制内容与使用相关示例创建的文件几乎相同
  • 您的代码让我找到了正确的方向 - 但它实际上需要在使用内存流之前处理 ZipArchive(加上 leaveOpen 需要设置为 true)。学分属于这个答案:stackoverflow.com/questions/12347775/…
猜你喜欢
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
相关资源
最近更新 更多