windhuan
11/29/2017 - 7:31 AM

Zip 解压缩

需添加引用ICSharpCode.SharpZipLib

    internal class ZipUtil
    {
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
            try
            {
                stream.Write(data, 0, data.Length);
            }
            finally
            {
                stream.Close();
                ms.Close();
            }
            return Convert.ToBase64String(ms.ToArray());
        }

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static byte[] Decompress(string param)
        {
            byte[] buffer = Convert.FromBase64String(param);
            MemoryStream ms = new MemoryStream(buffer);
            Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
            //这里要指明要读入的格式,要不就有乱码
            StreamReader reader = new StreamReader(sm, System.Text.Encoding.UTF8);
            try
            {
                return System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd());
            }
            finally
            {
                sm.Close();
                ms.Close();
            }
        }
    }