C#使用GZipStream压缩与解压字符串
这里是加压其实很简单,就是将传入的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(); } } } } }