by Dominic Zukiewicz
31. October 2007 12:18
I spent hours looking over 4 or 5 lines of code concerning these compression/decompression streams to find out why it was compressing and not decompressing.
The problem resulted in the decompression stream returning a zero length byte array for the resulting data. The problem also replicated itself as being too long. What went wrong?
This works!
//Decompress
private static string Uncompress(byte[] compressedData)
{
MemoryStream ms = new MemoryStream(compressedData);
MemoryStream uncompressedStream = new MemoryStream();
GZipStream gZip = new GZipStream(ms, CompressionMode.Uncompress);
byte[] buffer = new byte[1024];
int lengthOfBuffer = gZip.Read(0,buffer,buffer.Length);
while( lengthOfBuffer != 0 )
{
uncompressedStream.Write(buffer,0,lengthOfBuffer);
lengthOfBuffer = gZip.Read(0,buffer,buffer.Length);
}
return Encoding.Unicode.GetString( uncompressedStream.ToArray() );
}
Now for the subtle differences.
This returns back nothing, because you are not continuously reading from the stream. You need to pull more information out and write it to the MemoryStream.
private static string Uncompress(byte[] compressedData)
{
MemoryStream ms = new MemoryStream();
ms.Read(compressedData,0,compressedData.Length);
//ms.Position = 0; <--- This was missing!!
MemoryStream uncompressedStream = new MemoryStream();
GZipStream gZip = new GZipStream(ms, CompressionMode.Uncompress);
byte[] buffer = new byte[1024];
int lengthOfBuffer = gZip.Read(0,buffer,buffer.Length);
while( lengthOfBuffer != 0 )
{
uncompressedStream.Write(buffer,0,lengthOfBuffer);
//<-- Something is missing here!
}
return Encoding.Unicode.GetString( uncompressedStream.ToArray() );
}
This returns a string that is not the same length as the original. The reason is that you always assume that the buffer is the same size. When it reaches the end of the stream, the buffer may only be half full, and therefore the following code will not work:
//Decompress
private static string Uncompress(byte[] compressedData)
{
MemoryStream ms = new MemoryStream(compressedData);
MemoryStream uncompressedStream = new MemoryStream();
GZipStream gZip = new GZipStream(ms, CompressionMode.Uncompress);
byte[] buffer = new byte[1024];
int lengthOfBuffer = gZip.Read(0,buffer,buffer.Length);
while( lengthOfBuffer != 0 )
{
uncompressedStream..Write(buffer,0,buffer.Length); //<-- Problem is here!
lengthOfBuffer = gZip.Read(0,buffer,buffer.Length);
}
return Encoding.Unicode.GetString( uncompressedStream.ToArray() );
}
Check your code!!
9a92ef0d-8e38-46af-a326-1ddb255657b8|0|.0
Tags:
Framework