GZipStream compression problem ( Lost Byte )

≡放荡痞女 提交于 2019-11-28 13:27:22
Marc Gravell

Compression streams don't flush (and can't properly flush) until they are closed. You will need to close the GZipStream. Telling it not to close the underlying stream (one of the constructor arguments) will make this easier.

        //generating data
        int length = 100000;
        byte[] data = new byte[length];
        for (int i = 0; i < length; i++)
        {
            data[i] = System.Convert.ToByte(i % 100 + i % 50);
        }

        byte[] o;
        //serialization into memory stream
        IFormatter formatter = new BinaryFormatter();
        using (var ms = new MemoryStream())
        {
            formatter.Serialize(ms, data);
            ms.Seek(0, SeekOrigin.Begin);

            //GZip zip
            using(MemoryStream compressedStream = new MemoryStream())
            {
                using (var Compress = new GZipStream(compressedStream, CompressionMode.Compress, true))
                {
                    ms.CopyTo(Compress);
                }
                compressedStream.Seek(0, SeekOrigin.Begin);
                //GZip Unzip
                using (MemoryStream uncompressedStream = new MemoryStream())
                {
                    using (var Decompress = new GZipStream(compressedStream, CompressionMode.Decompress, true))
                    {
                        Decompress.CopyTo(uncompressedStream);
                    }
                    uncompressedStream.Seek(0, SeekOrigin.Begin);
                    var oo = formatter.Deserialize(uncompressedStream);
                    o = (byte[])oo;
                }
            }
            //deserialization from memory stream
            //POINT1

        }
        //checking
        Debug.Assert(data.Length == o.Length);
        for (int i = 0; i < data.Length; i++)
            Debug.Assert(data[i] == o[i]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!