c# - 不支持写入压缩流。使用 System.IO.GZipStream

标签 c# .net compression gzipstream

尝试使用 .NET 框架中包含的 GZipStream 类解压缩 (.gz) 文件时出现异常。我正在使用 MSDN 文档。这是异常(exception):

Writing to the compression stream is not supported.

这是应用程序源:

 try
 {
     var infile = new FileStream(@"C:\TarDecomp\TarDecomp\TarDecomp\bin\Debug\nick_blah-2008.tar.gz", FileMode.Open, FileAccess.Read, FileShare.Read);
     byte[] buffer = new byte[infile.Length];
     // Read the file to ensure it is readable.
     int count = infile.Read(buffer, 0, buffer.Length);
     if (count != buffer.Length)
     {
         infile.Close();
         Console.WriteLine("Test Failed: Unable to read data from file");
         return;
     }
     infile.Close();
     MemoryStream ms = new MemoryStream();
     // Use the newly created memory stream for the compressed data.
     GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress, true);
     Console.WriteLine("Decompression");
     compressedzipStream.Write(buffer, 0, buffer.Length); //<<Throws error here
     // Close the stream.
     compressedzipStream.Close();
     Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);
} catch {...}

在 compressedZipStream.write() 中抛出异常。

有什么想法吗?这个异常告诉我什么?

最佳答案

它告诉你,你应该调用Read而不是Write,因为它是解压!此外,内存流应该用数据构造,或者更确切地说,您应该将文件流直接传递给 GZipStream 构造函数。

应该如何完成的示例(还没有尝试编译它):

Stream inFile = new FileStream(@"C:\TarDecomp\TarDecomp\TarDecomp\bin\Debug\nick_blah-2008.tar.gz", FileMode.Open, FileAccess.Read, FileShare.Read);
Stream decodedStream = new MemoryStream();
byte[] buffer = new byte[4096];

using (Stream inGzipStream = new GZipStream(inFile, CompressionMode.Decompress))
{
    int bytesRead;
    while ((bytesRead = inGzipStream.Read(buffer, 0, buffer.Length)) > 0)
        decodedStream.Write(buffer, 0, bytesRead);
}

// Now decodedStream contains the decoded data

关于c# - 不支持写入压缩流。使用 System.IO.GZipStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354639/

相关文章:

c# - 从字符串填充 XDocument

c# - 从 C# 加载托管资源并将其作为流句柄传递给 native C++ 代码

c# - 操作数据集

java - 如何使用前导零字节抑制来压缩 Java 中的变量?

python - 如何用只包含数据但没有文件名的python解压xz文件?

c# - 尝试将记录插入到与其他两个表有关联的表时出错

c# - 使用 Reflection.Emit 创建一个方法,然后调用它

.net - 如何获取 'codebehind' 文件,以便默认创建 RC1 中的 ASP.NET-MVC View

c# - 通过 LibTiff.Net 从 Stream 加载的 Tiff 没有字段值

c++ - C/C++ 的压缩库能够处理数组中超过 32 位的元素