欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

gzip压缩与解压缩

程序员文章站 2024-03-14 09:13:28
...

话不多说,上代码。 GzipCompress在System.IO.Compression中。

/******************************************************************* 
 * FileName: GzipTool.cs
 * Author   : pilgrimzh
 * Date : 2016-08-12 13:08:21
 * Desc : 
 * 该工具用于对字节流进行Gzip压缩与解压缩
 * 
 * *******************************************************************/ 
 public  class GzipTool
    {

        /// <summary>
        /// gzip解压缩字节流
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static byte[] Decompress(byte[] src)
        {
            MemoryStream decompressedMs = new MemoryStream();
            MemoryStream srcMs = new MemoryStream(src);
            using (GZipStream gzipstream = new GZipStream(srcMs, CompressionMode.Decompress, true))
            {
                gzipstream.CopyTo(decompressedMs);
            }

            return decompressedMs.GetBuffer();
        }

        /// <summary>
        /// gzip压缩字节流
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static byte[] Compress(byte[] src)
        {
            MemoryStream compressedMs = new MemoryStream();
            
            using(GZipStream gzipstream = new GZipStream(compressedMs, CompressionMode.Compress, true))
            {
                MemoryStream srcMs = new MemoryStream(src);
                srcMs.CopyTo(gzipstream);
            }

            return compressedMs.GetBuffer();
        }
         
    }

转载于:https://my.oschina.net/pilgrimzh/blog/731713