Reputation: 39
i have a method which Decompress byte array and i need opposite of this function(mean Compress).i googeled a lot but didnot find exactly opposit of this function
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;
}
Upvotes: 0
Views: 5008
Reputation: 17402
You're over complicating the decompress part. You can achieve most what you want with purely streams and copying.
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();
}
}
Upvotes: 3