在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
这里是加压其实很简单,就是将传入的byte数组直接用GZipStream写到一个新的内存流里面去 public static byte[] Compress(byte[] bytes) { using (MemoryStream ms = new MemoryStream()) { GZipStream Compress = new GZipStream(ms, CompressionMode.Compress); Compress.Write(bytes, 0, bytes.Length); Compress.Close(); return ms.ToArray(); } }
因为我是用的.ne Framwork 4.0 所以GZipStream有CopyTo这个方法,但是4.0以下就没有这个方法。如果4.0以下只有在用一个BinaryReader 在去读取 public static byte[] Decompress(Byte[] bytes) { using (MemoryStream tempMs = new MemoryStream()) { using (MemoryStream ms = new MemoryStream(bytes)) { GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress); Decompress.CopyTo(tempMs); Decompress.Close(); return tempMs.ToArray(); } } }
下面是C#使用GZipStream压缩与解压字符串 using System; using System.Text; using System.IO; using System.IO.Compression; using System.Collections.Generic; namespace DatabaseUtilLib { public class ZipWrapper { public static string Compress(string str) { //因输入的字符串不是Base64所以转换为Base64,因为HTTP如果不传递Base64则会发生http 400错误 return Convert.ToBase64String(Compress(Encoding.Default.GetBytes(str))); } public static string Decompress(string str) { return Encoding.Default.GetString(Decompress(Convert.FromBase64String(str))); } public static byte[] Compress(byte[] bytes) { using (MemoryStream ms = new MemoryStream()) { GZipStream Compress = new GZipStream(ms, CompressionMode.Compress); Compress.Write(bytes, 0, bytes.Length); Compress.Close(); return ms.ToArray(); } } public static byte[] Decompress(Byte[] bytes) { using (MemoryStream tempMs = new MemoryStream()) { using (MemoryStream ms = new MemoryStream(bytes)) { GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress); Decompress.CopyTo(tempMs); Decompress.Close(); return tempMs.ToArray(); } } } } }
|
请发表评论