利用本文的方法,可以对任意对象进行压缩与解压缩。
using System.IO; using System.IO.Compression; /// <summary> /// 将数据压缩,并输出为 Base64String 格式。 /// </summary> /// <param name="data">原始数据。</param> private string Compress(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) { ms.Position = 0; using (MemoryStream ms2 = new MemoryStream()) { using (DeflateStream df = new DeflateStream(ms2, CompressionMode.Compress)) { byte[] buffer = new byte[4096]; int len = 0; while ((len = ms.Read(buffer, 0, buffer.Length)) > 0) df.Write(buffer, 0, len); } return Convert.ToBase64String(ms2.ToArray()); } } }
using System.IO; using System.IO.Compression; /// <summary> /// 将经过压缩并保存为 Base64String 格式的字符串解压。 /// </summary> /// <param name="base64String">经过压缩的 Base64String。</param> private byte[] Decompress(string base64String) { using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64String))) { ms.Position = 0; using (MemoryStream ms2 = new MemoryStream()) { using (DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress)) { byte[] buffer = new byte[4096]; int len = 0; while ((len = df.Read(buffer, 0, buffer.Length)) > 0) ms2.Write(buffer, 0, len); } return ms2.ToArray(); } } }