【IT168技术文档】
日前,使用framework中的gzip进行数据压缩解压缩,遇到两个问题,着实费了些力气才找大,拿出来晒晒
问题一:解压后数据少两个byte?!
上面这段是一开始我使用的代码,基本正常,可是解压后总是短两个byte。public static byte[] Compress(string s) { byte[] buf = System.Text.Encoding.UTF8.GetBytes(s); MemoryStream ms = new MemoryStream(); byte[] rb; GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true); gzip.Write(buf, 0, buf.Length); gzip.Flush(); ms.Position = 0; rb = new byte[ms.Length]; ms.Read(rb, 0, (int)ms.Length); gzip.Close(); ms.Close(); return rb; }
后来改为下面的代码,问题解决
public static byte[] Compress(string s) { byte[] buf = System.Text.Encoding.UTF8.GetBytes(s); MemoryStream ms = new MemoryStream(); byte[] rb; GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true); gzip.Write(buf, 0, buf.Length); gzip.Flush(); gzip.Close(); ms.Position = 0; rb = new byte[ms.Length]; ms.Read(rb, 0, (int)ms.Length); ms.Close(); return rb; }