我很抱歉这个保守的标题和我的问题本身,但我迷路了。
ICsharpCode.ZipLib提供的示例不包括我正在搜索的内容。我想通过将其放入InflaterInputStream(ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream)中来解压缩byte[]
我找到了一个解压缩函数,但它不起作用。
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();
}它在第(size= stream.Read(writeData,0,writeData.Length);)行抛出一个异常,说明它有一个无效的头部。
我的问题不是如何修复函数,这个函数不是随库一起提供的,我只是发现它googling.My问题是,如何像InflaterStream函数一样解压,但没有例外。
再次感谢--很抱歉这个保守的问题。
发布于 2009-04-12 11:19:01
好的,听起来数据是不合适的,否则代码就会正常工作。(诚然,我会对流使用"using“语句,而不是显式地调用Close。)
你的数据是从哪里来的?
发布于 2013-12-12 21:59:23
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();
}发布于 2009-04-12 11:23:59
为什么不使用System.IO.Compression.DeflateStream类(从.Net 2.0开始提供)?这使用相同的压缩/解压缩方法,但不需要额外的库依赖。
从.Net 2.0开始,只有在需要文件容器支持的情况下才需要ICSharpCode.ZipLib。
https://stackoverflow.com/questions/741591
复制相似问题