1

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.

sid
  • 35
  • 4

1 Answers1

0
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.

  • 2
    When the code is several lines long, and you change only a small part of the original code, you should highlight the part that makes up the solution. And possibly explain what you changed. – Rubidium 37 Sep 06 '22 at 09:31
  • Wow - can't believe I missed that - thanks! – sid Sep 06 '22 at 17:35
  • Thanks Rubidium. But I don't know how to highlight the sentence in the code. Could you tell me the way to highlight? – ThrowDevNull Sep 07 '22 at 02:49