ZlibStream... must I know the uncompressed size???

Feb 7, 2013 at 10:08 PM
I have a byte array which is some zlib compressed data, but I don't know the size of the uncompressed data. I'm struggling to see how I can make use of the ZlibStream class.

bytes[] bytes = getTheBytes();
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
Compression.ZlibStream zs = new Compression.ZlibStream(ms, System.IO.Compression.CompressionMode.Decompress, false); 
byte[] decompressed = new byte[???];
int read = zs.read(decompressed, 0, ???);
Am I being daft?

Thank you all...
Feb 8, 2013 at 9:15 PM
Edited Feb 8, 2013 at 9:16 PM
Ooohhhhhhhhhh, I get it... the read method of the ZlibStream populates the receiving array with decompressed bytes and returns the number of decompressed bytes read. The compressed stream being read and the decompressed stream being written to are advanced independently.
string header = null; // Will eventually hold the decompressed UTF8 string
#region Decompress zlib'd data
  byte[] buff = new byte[1024];
  using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
    using (Compression.ZlibStream zs = new Compression.ZlibStream(ms, System.IO.Compression.CompressionMode.Decompress, false))
      using (System.IO.MemoryStream decomp = new System.IO.MemoryStream())
         int n;
         while ((n = zs.Read(buff, 0, buff.Length)) != 0)
           decomp.Write(buff, 0, n);
         decomp.Seek(0, System.IO.SeekOrigin.Begin);
         System.IO.StreamReader sr = new System.IO.StreamReader(decomp, System.Text.Encoding.UTF8);
         header = sr.ReadToEnd();
Feb 10, 2013 at 3:06 PM
Edited Feb 10, 2013 at 3:25 PM
It could be simpler if you want to read the data into a string...
 string str;
 MemoryStream compressed = new MemoryStream(data)
 using (ZlibStream zls = new ZlibStream(compressed, CompressionMode.Decompress, true))
 using (StreamReader reader = new StreamReader(zls))
    str = reader.ReadToEnd();