我有一个解压缩字节数组的方法,我需要与此功能相反的方法(平均压缩)。我做了很多事情,但并未发现与此功能完全相反
public static byte[] Decompress(byte[] B)
{
MemoryStream ms = new MemoryStream(B);
GZipStream gzipStream = new GZipStream((Stream)ms, CompressionMode.Decompress);
byte[] buffer = new byte[4];
ms.Position = checked(ms.Length - 5L);
ms.Read(buffer, 0, 4);
int count = BitConverter.ToInt32(buffer, 0);
ms.Position = 0L;
byte[] AR = new byte[checked(count - 1 + 1)];
gzipStream.Read(AR, 0, count);
gzipStream.Dispose();
ms.Dispose();
return AR;
}
答案 0 :(得分:1)
您已经使解压缩部分复杂化了。您可以通过纯粹的流和复制来实现大部分所需的功能。
private byte[] Compress(byte[] data)
{
using (var compressedStream = new MemoryStream())
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
zipStream.Write(data, 0, data.Length);
return compressedStream.ToArray();
}
}
private byte[] Decompress(byte[] data)
{
using (var compressedStream = new MemoryStream(data))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}
}