1

I'm using ICSharpCode.SharpZipLib.dll for compress and decompress data.
I have the following code that performs inflation of data:

public static byte[] ZLibDecompress(byte[] zLibCompressedBuffer)
{
    byte[] resBuffer = null;

    MemoryStream mInStream = new MemoryStream(zLibCompressedBuffer);
    MemoryStream mOutStream = new MemoryStream(zLibCompressedBuffer.Length);
    InflaterInputStream infStream = new InflaterInputStream(mInStream);

    mInStream.Position = 0;

    try
    {
        byte[] tmpBuffer = new byte[zLibCompressedBuffer.Length];
        int read = 0;

        do
        {
            read = infStream.Read(tmpBuffer, 0, tmpBuffer.Length);
            if (read > 0)
                mOutStream.Write(tmpBuffer, 0, read);

        } while (read > 0);

        resBuffer = mOutStream.ToArray();
    }
    finally
    {
        infStream.Close();
        mInStream.Close();
        mOutStream.Close();
    }

    return resBuffer;
}

This code actually works, and now I want to compress the result back.
So this is my code:

public static byte[] ZLibCompress(byte[] buffer)
{
    byte[] resBuffer = null;

    MemoryStream mOutStream = new MemoryStream(buffer.Length);
    DeflaterOutputStream defStream = new DeflaterOutputStream(mOutStream);

    try
    {
        defStream.Write(buffer, 0, buffer.Length);
        defStream.Flush();
        defStream.Finish();

        resBuffer = mOutStream.ToArray();
    }
    finally
    {
        defStream.Close();
        mOutStream.Close();
    }

    return resBuffer;
}

But two result arrays of two functions arn't equal:

byte[] unCompBuffer = ZipUtils.ZLibDecompress(zLibBuffer);
byte[] compBuffer = ZipUtils.ZLibCompress(unCompBuffer);
bool eq = compBuffer.SequenceEqual(zLibBuffer);

eq is false.
Any ideas?
Thank you for ahead.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
rodnower
  • 1,365
  • 3
  • 22
  • 30

1 Answers1

3

Where does the compressed buffer come from? Was it compressed by SharpZipLib too? With the same compression level and options? If not, you shouldn't expect the decompressed/recompressed buffer to be equal to the original...

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    Correct- DEFLATE compression doesn't guarantee that the compressed streams generated by different compressors will be equal. DEFLATE compression says only that on decompression, the decompressed stream will be equal to the original uncompressed stream. Things that cause the compressed byte streams to differ are dictionary options, window size (compression level), and others. – Cheeso May 08 '11 at 16:40