Lamloumi Afif Lamloumi Afif - 6 months ago 52
C# Question

Using Gzip to compress/decompress an array of bytes

I need to compress an array of bytes. So I wrote this snippet :

class Program
static void Main()
var test = "foo bar baz";

var compressed = Compress(Encoding.UTF8.GetBytes(test));
var decompressed = Decompress(compressed);
Console.WriteLine("size of initial table = " + test.Length);
Console.WriteLine("size of compressed table = " + compressed.Length);
Console.WriteLine("size of decompressed table = " + decompressed.Length);

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

static byte[] Decompress(byte[] data)
using (var compressedStream = new MemoryStream(data))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
return resultStream.ToArray();

The problem is that I get this output :


I don't understand why the size of the compressed array is greater than the decompressed one !

Any ideas?


after @spender's comment: if I change
string for example :

var test = "foo bar baz very long string for example hdgfgfhfghfghfghfghfghfghfghfghfghfghfhg";

I get different result. So what is the minimum size of the initial array to be compressed ?


Compressed file has headers and it increases the file size, when the input size is very small the output can be even bigger as you see. try it with a file with bigger size.