gpt4 book ai didi

c# - 如何将 ICSharpCode.ZipLib 与流一起使用?

转载 作者:太空狗 更新时间:2023-10-30 01:12:18 25 4
gpt4 key购买 nike

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

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

我找到了一个解压功能,但它不起作用。

    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();
}

它在 line(size = stream.Read(writeData, 0, writeData.Length);) 处抛出一个异常,说它有一个无效的标题。

我的问题不是如何修复这个函数,这个函数没有随库一起提供,我只是用谷歌搜索找到它。我的问题是,如何像函数对 InflaterStream 一样解压缩,但没有异常(exception)。

再次感谢 - 很抱歉这个保守的问题。

最佳答案

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();
}

关于c# - 如何将 ICSharpCode.ZipLib 与流一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/741591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com