C#使用DeflateStream压缩与解压

/// 
    /// 简单的压缩
    /// 
    public static class CompressHelper
    {
        /// 
        /// 压缩字符串
        /// 
        /// 
        /// 
        public static byte[] CompressString(string str)
        {
            return CompressBytes(Encoding.UTF8.GetBytes(str));
        }

        /// 
        /// 压缩二进制
        /// 
        /// 
        /// 
        public static byte[] CompressBytes(byte[] str)
        {
            var ms = new MemoryStream(str) {Position = 0};
            var outms = new MemoryStream();
            using (var deflateStream = new DeflateStream(outms, CompressionMode.Compress, true))
            {
                var buf = new byte[1024];
                int len;
                while ((len = ms.Read(buf, 0, buf.Length)) > 0)
                    deflateStream.Write(buf, 0, len);
            }
            return outms.ToArray();
        }
        /// 
        /// 解压字符串
        /// 
        /// 
        /// 
        public static string DecompressString(byte[] str)
        {
            return Encoding.UTF8.GetString(DecompressBytes(str));
        }
        /// 
        /// 解压二进制
        /// 
        /// 
        /// 
        public static byte[] DecompressBytes(byte[] str)
        {
            var ms = new MemoryStream(str) {Position = 0};
            var outms = new MemoryStream();
            using (var deflateStream = new DeflateStream(ms, CompressionMode.Decompress, true))
            {
                var buf = new byte[1024];
                int len;
                while ((len = deflateStream.Read(buf, 0, buf.Length)) > 0)
                    outms.Write(buf, 0, len);
            }
            return outms.ToArray();
        }
    }

你可能感兴趣的:(Asp.Net,C#,windows,c#,byte,string,class)