Micah
Micah

Reputation: 116070

How do I determine how large to make my buffer when using GzipStream?

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?

Upvotes: 1

Views: 386

Answers (2)

Rune Grimstad
Rune Grimstad

Reputation: 36300

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.

Upvotes: 0

leppie
leppie

Reputation: 117220

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();
}

Upvotes: 4

Related Questions