Using GZipStream not behaving how I would expect

160 Views Asked by At

I have the following code:

string testString = "test abc";
var bytes = Encoding.UTF8.GetBytes(testString);

using var memoryStream = new MemoryStream();
using var gzipStream = new GZipStream(memoryStream, CompressionLevel.SmallestSize);
gzipStream.Write(bytes, 0, bytes.Length);

var dbytes = memoryStream.ToArray();

My understanding is that this code will compress the string. However, when I try to decompress this, it returns an empty byte array:

using var memoryStream2 = new MemoryStream(dbytes);
using var outputStream = new MemoryStream();
using var decompressStream = new GZipStream(memoryStream2, CompressionMode.Decompress);
decompressStream.CopyTo(outputStream);
var returnBytes = outputStream.ToArray();

string stest2 = Encoding.UTF8.GetString(returnBytes)!;
Console.WriteLine(stest2); // empty

It also seems to actually make the byte array bigger after compression, but I guess this is because the string is so small the overhead of compression causes the size to increase.

Please can someone point me to what I'm doing wrong here.

1

There are 1 best solutions below

3
ThrowDevNull On BEST ANSWER
string testString = "test abc";
var bytes = Encoding.UTF8.GetBytes(testString);

using var memoryStream = new MemoryStream();
using var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true);
gzipStream.Write(bytes, 0, bytes.Length);
gzipStream.Close();

var dbytes = memoryStream.ToArray();

using var memoryStream2 = new MemoryStream(dbytes);
using var outputStream = new MemoryStream();
using var decompressStream = new GZipStream(memoryStream2, CompressionMode.Decompress);
decompressStream.CopyTo(outputStream);
var returnBytes = outputStream.ToArray();

string stest2 = Encoding.UTF8.GetString(returnBytes)!;
Console.WriteLine(stest2); // works well

Thanks.