【问题标题】:DeflateStream CopyTo writes nothing and throws no exceptionsDeflateStream CopyTo 什么都不写,也不抛出异常
【发布时间】:2013-10-03 17:54:55
【问题描述】:

我基本上是直接从 msdn 复制了这个代码示例,只做了一些微小的改动。 CopyTo 方法默默地失败了,我不知道为什么。什么会导致这种行为?它正在传递一个 78 KB 的压缩文件夹,其中包含一个文本文件。返回的FileInfo 对象指向一个 0 KB 的文件。不会抛出异常。

    public static FileInfo DecompressFile(FileInfo fi)
    {
        // Get the stream of the source file.
        using (FileStream inFile = fi.OpenRead())
        {
            // Get original file extension, 
            // for example "doc" from report.doc.cmp.
            string curFile = fi.FullName;
            string origName = curFile.Remove(curFile.Length
                    - fi.Extension.Length);

            //Create the decompressed file.
            using (FileStream outFile = File.Create(origName))
            {
                // work around for incompatible compression formats found
                // here http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html
                inFile.ReadByte();
                inFile.ReadByte();

                using (DeflateStream Decompress = new DeflateStream(inFile,
                    CompressionMode.Decompress))
                {
                    // Copy the decompression stream 
                    // into the output file.
                    Decompress.CopyTo(outFile);

                    return new FileInfo(origName);
                }
            }
        }
    }

【问题讨论】:

  • 您要读取和解压缩什么类型的文件? .gz、.zip 还是其他文件?
  • @huntharo 这是一个 .zip。

标签: c# .net compression zip


【解决方案1】:

在评论中您说您正在尝试解压缩 zip 文件。 DeflateStream 类不能像这样在 zip 文件中使用。您提到的MSDN example 使用DeflateStream 创建单独的压缩文件,然后将它们解压缩。

虽然 zip 文件可能使用相同的算法(不确定),但它们不仅仅是单个文件的压缩版本。 zip 文件是一个容器,可以容纳许多文件和/或文件夹。

如果您可以使用 .NET Framework 4.5,我建议您使用新的 ZipFileZipArchive 类。如果您必须使用较早的框架版本,您可以使用免费库(例如 DotNetZipSharpZipLib)。

【讨论】:

  • 不幸的是,我使用的是 .NET 4。我最初尝试使用 Zipfile 类,但意识到这不是一个选项。我可能不得不使用其中一个第三方库,但我不想这样做。
猜你喜欢
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
相关资源
最近更新 更多