如何在流中使用ICSharpCode.ZipLib?

我对保守的头衔和我的问题本身感到非常抱歉,但我迷路了。

ICsharpCode.ZipLib提供的示例不包括我正在搜​​索的内容。 我想通过将其放入InflaterInputStream(ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream)来解压缩byte []

我找到了解压缩function,但它不起作用。

public static byte[] Decompress(byte[] Bytes) { ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream stream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(new MemoryStream(Bytes)); MemoryStream memory = new MemoryStream(); byte[] writeData = new byte[4096]; int size; while (true) { size = stream.Read(writeData, 0, writeData.Length); if (size > 0) { memory.Write(writeData, 0, size); } else break; } stream.Close(); return memory.ToArray(); } 

它在行引发exception(size = stream.Read(writeData,0,writeData.Length);)说它有一个无效的头。

我的问题不是如何修复函数,这个函数没有提供库,我只是发现它google搜索。我的问题是,如何解压缩函数与InflaterStream相同的方式,但没有例外。

再次感谢 – 抱歉保守的问题。

嗯,这听起来像数据是不合适的,否则代码将正常工作。 (不可否认,我会为流使用“using”语句,而不是显式调用Close 。)

你从哪里得到你的数据?

为什么不使用System.IO.Compression.DeflateStream类(自.Net 2.0起可用)? 这使用相同的压缩/解压缩方法,但不需要额外的库依赖。

从.Net 2.0开始,如果需要文件容器支持,则只需要ICSharpCode.ZipLib。

lucene中的代码非常好。

 public static byte[] Compress(byte[] input) { // Create the compressor with highest level of compression Deflater compressor = new Deflater(); compressor.SetLevel(Deflater.BEST_COMPRESSION); // Give the compressor the data to compress compressor.SetInput(input); compressor.Finish(); /* * Create an expandable byte array to hold the compressed data. * You cannot use an array that's the same size as the orginal because * there is no guarantee that the compressed data will be smaller than * the uncompressed data. */ MemoryStream bos = new MemoryStream(input.Length); // Compress the data byte[] buf = new byte[1024]; while (!compressor.IsFinished) { int count = compressor.Deflate(buf); bos.Write(buf, 0, count); } // Get the compressed data return bos.ToArray(); } public static byte[] Uncompress(byte[] input) { Inflater decompressor = new Inflater(); decompressor.SetInput(input); // Create an expandable byte array to hold the decompressed data MemoryStream bos = new MemoryStream(input.Length); // Decompress the data byte[] buf = new byte[1024]; while (!decompressor.IsFinished) { int count = decompressor.Inflate(buf); bos.Write(buf, 0, count); } // Get the decompressed data return bos.ToArray(); }