c# Deflate压缩与解压缩函数

来源:互联网 发布:遂溪农村淘宝 编辑:程序博客网 时间:2024/04/29 11:05
1 /// <summary> 2 /// Deflate压缩函数 3 /// </summary> 4 /// <param name="strSource"></param> 5 /// <returns></returns> 6 public string DeflateCompress(string strSource) 7 { 8     if (strSource == null || strSource.Length > 8 * 1024) 9         throw new System.ArgumentException("字符串为空或长度太大!");10     byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strSource);11     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())12     {13         using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true))14         {15             stream.Write(buffer, 0, buffer.Length);16             stream.Close();17         }18     byte[] compressedData = ms.ToArray();19     ms.Close();20     return Convert.ToBase64String(compressedData);      //将压缩后的byte[]转换为Base64String21     }22 }
1 /// <summary> 2 /// Deflate解压函数 3 /// JS:var details = eval('(' + utf8to16(zip_depress(base64decode(hidEnCode.value))) + ')')对应的C#压缩方法 4 /// </summary> 5 /// <param name="strSource"></param> 6 /// <returns></returns> 7 public string DeflateDecompress(string strSource) 8 { 9     byte[] buffer = Convert.FromBase64String(strSource);10     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())11     {12         ms.Write(buffer, 0, buffer.Length);13         ms.Position = 0;14         using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))15         {16             stream.Flush();17             int nSize = 16 * 1024 + 256;    //假设字符串不会超过16K18             byte[] decompressBuffer = new byte[nSize];19             int nSizeIncept = stream.Read(decompressBuffer, 0, nSize);20             stream.Close();21             return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept);   //转换为普通的字符串22         }23     }24 }


0 0
原创粉丝点击