C# 如何将ICSharpCode.ZipLib与流一起使用?
对于保守党的头衔和我的问题本身,我感到非常抱歉,但我迷路了 ICsharpCode.ZipLib提供的示例不包括我正在搜索的内容。 我想通过将字节[]放入InflaterInputStream(ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream)来解压缩它 我找到了一个解压函数,但它不起作用C# 如何将ICSharpCode.ZipLib与流一起使用?,c#,byte,sharpziplib,compression,C#,Byte,Sharpziplib,Compression,对于保守党的头衔和我的问题本身,我感到非常抱歉,但我迷路了 ICsharpCode.ZipLib提供的示例不包括我正在搜索的内容。 我想通过将字节[]放入InflaterInputStream(ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream)来解压缩它 我找到了一个解压函数,但它不起作用 public static byte[] Decompress(byte[] Bytes) {
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);)抛出一个异常,表示它的头无效
我的问题不是如何修复函数,这个函数没有随库提供,我只是在谷歌上找到它。我的问题是,如何像函数对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();
}