0

Why don't I get the same content after decompressing and compressing-back a byte-array with DeflateStream?

The code:

byte[] originalcontent = Same Byte Array Content
byte[] decompressedBytes;
byte[] compressedBackBytes;

// Decompress the original byte-array
using (Stream contentStream = new MemoryStream(originalcontent, false))
using (var zipStream = new DeflateStream(contentStream, CompressionMode.Decompress))
using (var decStream = new MemoryStream())
{
    zipStream.CopyTo(decStream);
    decompressedBytes = decStream.ToArray();
}

// Compress the byte-array back
using (var input = new MemoryStream(decompressedBytes, true))
using (var compressStream = new MemoryStream())
using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress))
{
    input.CopyTo(compressor);
    compressedBackBytes = compressStream.ToArray();
}

Why originalcontent != compressedBackBytes ?

Roi Bar
  • 105
  • 11
  • 1
    maybe flush your stream https://stackoverflow.com/questions/10599596/compress-and-decompress-a-stream-with-compression-deflatestream – Any Moose Sep 05 '18 at 18:28
  • 1
    Why you first decompress, and then compress? Why not compress, and then decompress? – DanB Sep 05 '18 at 18:28
  • Was the original compresssed data generated using the same code using the same options? – Robert Sep 05 '18 at 18:28
  • Flushing the stream as written in https://stackoverflow.com/questions/10599596/compress-and-decompress-a-stream-with-compression-deflatestream – Roi Bar Nov 07 '18 at 12:28

1 Answers1

1

It looks like you did everything properly, until you took the original input stream and overwrote your compressor, which contains your decompressed bytes. You need to place your compressor bytes into compressedBackBytes.

Your input (beginning with the decompress) seems it copies the decompressed bytes into it; then later you copy it to the compressor, which overwrites what you just decompressed.

Maybe you meant something like

compressedBackBytes = compressor.ToArray();
Andrew Jay
  • 1,412
  • 1
  • 12
  • 17