I'm trying to decompress a GZipStream. The problem is that the "Length" property on the stream throws a "NotSupported" exception. How do I know what size to make my buffer when I'm reading the bytes from the stream? Since it's compressed I don't know how large the uncompressed version will be. Any suggestions?
+3
A:
Why do you need that?
public static byte[] Decompress(this byte[] data)
{
var ms = new MemoryStream(data);
var s = new GZipStream(ms, CompressionMode.Decompress);
var output = new MemoryStream();
byte[] buffer = new byte[8192];
int read = 0;
while ((read = s.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return output.ToArray();
}
leppie
2009-06-11 06:25:52
+1 for the example :-)
Rune Grimstad
2009-06-11 06:29:31
I'm struggling with this example a little bit. I have an HttpResponseStream that is gzipped how do I use this in that context?
Micah
2009-06-11 06:53:10
I figured it out. I had to read all the bytes in to a memory stream first just like you do in the decompress routine, and then pass those bytes in. Thanks! Screen scraping sucks.
Micah
2009-06-11 07:07:43
Instead of building the `ms` MemoryStream from `data`, you just pass in the HttpResponseStream into the GZipStream instance, I'd say.
jerryjvl
2009-06-11 07:09:38
A:
Depending on what you are going to do with it you could write the uncompressed contents to either a MemoryStream or FileStream. They can both be set up to extend their buffers as needed.
The MemoryStream also has a ToArray method that extracts its contents as a byte array.
Rune Grimstad
2009-06-11 06:29:05