0

I want to compress a binary file in memory using System.IO.Compression.GZipStream. For this, I am using the following method

public byte[] Encrypt()
{
    var payload = GetPayload();
    Console.WriteLine("[!] Payload Size: {0} bytes", payload.Length);

    using (var compressedStream = new MemoryStream(payload))
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
    using (var resultStream = new MemoryStream())
    {
        zipStream.CopyTo(resultStream);
        return resultStream.ToArray();
    }
}

But while .CopyTo, I am getting System.NotSupportedException: Stream does not support reading.

tbhaxor
  • 1,659
  • 2
  • 13
  • 43

1 Answers1

2

You need to "inverse" your logic: create GZipStream over empty MemoryStream and copy your original content into this gzip stream:

using var compressedData = new MemoryStream();
using var gzip = new GZipStream(compressedData);
originalUncompressedStream.CopyTo(gzip); // <- "magic" happens here
gzip.Flush();

// and "rewind" result stream back to beginning (for next reads)
compressedData.Position = 0;
Dmitry
  • 16,110
  • 4
  • 61
  • 73