Exemple #1
0
        private static DeflateStream CreateDeflateStreamForReading(Stream stream, bool leaveOpen)
        {
            if (!stream.CanRead)
            {
                throw new ArgumentException("The stream must support reading", "stream");
            }

            int compressionMethodAndFlags = stream.ReadByte();
            int flags = stream.ReadByte();

            if (compressionMethodAndFlags == -1 || flags == -1)
            {
                throw new EndOfStreamException();
            }

            if (((compressionMethodAndFlags << 8) + flags) % 31 != 0)
            {
                throw new System.FormatException("stream is not a valid zlib stream");
            }

            int compressionMethod = compressionMethodAndFlags & 0xF;

            if (compressionMethod != 8)
            {
                throw new NotSupportedException("Compression method " + compressionMethod + " is not supported");
            }

            if ((flags & 0x10) != 0)
            {
                // skip DICTID
                byte[] buffer = new byte[4];
                if (stream.Read(buffer, 0, 4) < 4)
                {
                    throw new EndOfStreamException();
                }
            }

            long offset = stream.Position;
            long length = stream.Length - offset - 4; // - 4 for ADLER-32 checksum

            SubStream subStream = new SubStream(stream, offset, length, leaveOpen);

            try {
                return(new DeflateStream(subStream, CompressionMode.Decompress, false));
            } catch {
                subStream.Dispose();
                throw;
            }
        }