Spook
Spook

Reputation: 25927

GZipStream does not decompress data correctly

I'm trying to compress data with GZipStream. The code is quite straightforward:

// Serialize
var ms = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms, result);
ms.Seek(0, SeekOrigin.Begin);

// Compress
var ms2 = new MemoryStream();
GZipStream zipStream = new GZipStream(ms2, CompressionMode.Compress);
ms.CopyTo(zipStream);
zipStream.Flush();

// Test
ms2.Seek(0, SeekOrigin.Begin);
var ms3 = new MemoryStream();
var unzipStream = new GZipStream(ms2, CompressionMode.Decompress);
unzipStream.CopyTo(ms3);

System.Diagnostics.Debug.WriteLine($"{ms.Length} =? {ms3.Length}");

Results should be equal, but I'm getting:

244480 =? 191481

Is the GZipStream unable to decompress stream compressed by itself? Or am I doing something wrong?

Upvotes: 1

Views: 178

Answers (1)

canton7
canton7

Reputation: 42225

From the docs of GZipStream.Flush:

The current implementation of this method does not flush the internal buffer. The internal buffer is flushed when the object is disposed.

That fits in with not enough data being written to ms2. Try wrapping zipStream in a using block instead:

var ms2 = new MemoryStream();
using (GZipStream zipStream = new GZipStream(ms2, CompressionMode.Compress))
{
    ms.CopyTo(zipStream);
}

Upvotes: 2

Related Questions