1

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?

Micah
  • 111,873
  • 86
  • 233
  • 325

2 Answers2

4

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
  • 115,091
  • 17
  • 196
  • 297
  • 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 Jun 11 '09 at 06:53
  • 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 Jun 11 '09 at 07:07
  • 1
    Instead of building the `ms` MemoryStream from `data`, you just pass in the HttpResponseStream into the GZipStream instance, I'd say. – jerryjvl Jun 11 '09 at 07:09
  • don't forget that both `MemoryStream` and `GZipStream` implement `IDisposable` interface... As shown, your method will leak memory – taiji123 Oct 04 '22 at 15:01
0

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
  • 35,612
  • 10
  • 61
  • 76