.Net zlib inflate with .Net 4.5

前端 未结 3 1138
悲哀的现实
悲哀的现实 2020-12-11 05:43

According to MSDN in .Net 4.5 System.IO.Compression is based on zlib.
I am trying now to change my current interop based reading from a zlib deflated stream from a non .

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 06:48

    The answer above is correct but isn't exactly clear on the "why". The first two bytes of a raw ZLib stream provide details about the type of compression used. Microsoft's DeflateStream class in System.Io.Compression doesn't understand these. The fix is as follows:

    using (MemoryStream ms = new MemoryStream(data))
    {
        MemoryStream msInner = new MemoryStream();
    
        // Read past the first two bytes of the zlib header
        ms.Seek(2, SeekOrigin.Begin);
    
        using (DeflateStream z = new DeflateStream(ms, CompressionMode.Decompress))
        {
            z.CopyTo(msInner);
    

    In this example, data is a Byte[] with the raw Zlib file. After loading it into a MemoryStream, we simply "seek" past the first two bytes.

    The post explains what a Zlib header looks like if you are looking at the raw bytes.

    What does a zlib header look like?

提交回复
热议问题