C#学习教程:GZipStream压缩问题(丢失字节)分享


GZipStream压缩问题(丢失字节)

我对GZip Serializer有一些奇怪的问题。

尝试使用数据序列化对象。

以下代码给出结果( 在调试中的POINT1 ):ms.Length = 100028和uncompressedStream.Length = 100027

POINT1之后有exception“解析完成之前遇到的流结束。”,我认为是这个丢失字节的结果。

我正在使用.net 4.0。

//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); } //serialization into memory stream IFormatter formatter = new BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, data); ms.Seek(0, SeekOrigin.Begin); //GZip zip MemoryStream compressedStream = new MemoryStream(); var Compress = new GZipStream(compressedStream, CompressionMode.Compress); ms.CopyTo(Compress); compressedStream.Seek(0, SeekOrigin.Begin); //GZip Unzip MemoryStream uncompressedStream = new MemoryStream(); var Decompress = new GZipStream(compressedStream, CompressionMode.Decompress); Decompress.CopyTo(uncompressedStream); uncompressedStream.Seek(0, SeekOrigin.Begin); //deserialization from memory stream //POINT1 var oo = formatter.Deserialize(uncompressedStream); var o = (byte[])oo; //checking Assert.AreEqual(data.Length, o.Length); for (int i = 0; i < data.Length; i++) Assert.AreEqual(data[i], o[i]); 

压缩流在关闭之前不会刷新(并且无法正确刷新)。 您需要关闭GZipStream 。 告诉它不要关闭底层流(构造函数参数之一)将使这更容易。

上述就是C#学习教程:GZipStream压缩问题(丢失字节)分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—猴子技术宅(www.ssfiction.com)

  //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]); 

本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ssfiction.com/ckf/1032014.html

发表评论

邮箱地址不会被公开。 必填项已用*标注