简介:此类表示 GZip 数据格式,它使用无损压缩和解压缩文件的行业标准算法。这种格式包括一个检测数据损坏的循环冗余校验值。GZip 数据格式使用的算法与 DeflateStream 类的算法相同,但它可以扩展以使用其他压缩格式。这种格式可以通过不涉及专利使用权的方式轻松实现。gzip 的格式可以从 RFC 1952“GZIP file format specification 4.3(GZIP 文件格式规范 4.3)GZIP file format specification 4.3(GZIP 文件格式规范 4.3)”中获得。此类不能用于压缩大于 4 GB 的文件
var list = new List<dataSource>(); for (int i = 0; i < 1000; i++) { list.Add(new dataSource { lemmaId = i.ToString(), pic = "图片问题" + i, title = $"这是第{i}条数据", url = "http://www.baidu.com" }); } //进行压缩数据 MemoryStream responseStream = new MemoryStream(); using (GZipStream compressedStream = new GZipStream(responseStream, CompressionMode.Compress, true)) { MemoryStream st = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(list))); Console.WriteLine($"原始数据长度为={st.Length}"+ " "); byte[] buffer = new byte[st.Length]; int checkCounter = st.Read(buffer, 0, buffer.Length); if (checkCounter != buffer.Length) throw new ApplicationException(); compressedStream.Write(buffer, 0, buffer.Length); } responseStream.Position = 0; var kk = responseStream; var txt = Encoding.UTF8.GetString(kk.ToArray()); Console.WriteLine($"压缩后数据长度为={responseStream.Length},压缩结果为={txt}"+" "); //解压数据 MemoryStream source = new MemoryStream(); using (GZipStream gs = new GZipStream(kk, CompressionMode.Decompress, true)) { //从压缩流中读出所有数据 byte[] bytes = new byte[4096]; int n; while ((n = gs.Read(bytes, 0, bytes.Length)) != 0) { source.Write(bytes, 0, n); } } var txt1 = Encoding.UTF8.GetString(source.ToArray()); Console.WriteLine($"解压后数据长度为={source.Length},压缩结果为={txt1}" + " ");
结果: