Problem with the GZipStream class and small streams (apparently smaller than 4096 bytes)  
Author Message
Fabio Scagliola





PostPosted: .NET Base Class Library, Problem with the GZipStream class and small streams (apparently smaller than 4096 bytes) Top

Hello!

I have a problem using the System.IO.Compression.GZipStream class. I wrote the following methods to compress and decompress arrays of bytes.

private static byte[] Compress(byte[] array)
{
MemoryStream stream = new MemoryStream();
GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress);
gZipStream.Write(array, 0, array.Length);
return stream.ToArray();
}

private static byte[] Decompress(byte[] array)
{
MemoryStream stream = new MemoryStream();
GZipStream gZipStream = new GZipStream(new MemoryStream(array), CompressionMode.Decompress);
byte[] b = new byte[4096];
while (true)
{
int n = gZipStream.Read(b, 0, b.Length);
if (n > 0)
stream.Write(b, 0, n);
else
break;
}
return stream.ToArray();
}

In the Decompress method, if the array of bytes is small (apparently smaller than 4096 bytes), then the Read method returns 0 regardless the size of the b buffer. Also, replacing the while block with the following one, if the array of bytes is small, then the ReadByte method returns -1.

while (true)
{
int n = gZipStream.ReadByte();
if (n != -1)
stream.WriteByte((byte)n);
else
break;
}

Is this happening because the GZipStream class internally uses a 4 KB buffer Anyway, how could I solve the problem

Thank you,
Fabio




.NET Development6  
 
 
BillWert - MSFT





PostPosted: .NET Base Class Library, Problem with the GZipStream class and small streams (apparently smaller than 4096 bytes) Top

By adding calls to Close() on the gZipStream object your code works fine:

private static byte[] Compress(byte[] array)

{

MemoryStream stream = new MemoryStream();

GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress);

gZipStream.Write(array, 0, array.Length);

gZipStream.Close();

return stream.ToArray();

}

private static byte[] Decompress(byte[] array)

{

MemoryStream stream = new MemoryStream();

GZipStream gZipStream = new GZipStream(new MemoryStream(array), CompressionMode.Decompress);

byte[] b = new byte[4096];

while (true)

{

int n = gZipStream.Read(b, 0, b.Length);

if (n > 0)

stream.Write(b, 0, n);

else

gZipStream.Close();

break;

}

return stream.ToArray();

}