C# 使用GZipStream实现压缩和解压缩

概述

之前做项目,涉及到存入到数据库或者http传输的数据量比较大,这个时候,就需要考虑在存入数据库或者发送传输之前,将数据压缩下,当从数据库中取出时,再解压还原数据。特地找了下发现有GZipStream可以实现这个功能。此类表示gzip数据格式,该格式使用行业标准算法进行无损文件压缩和解压缩。该格式包括用于检测数据损坏的循环冗余校验值。gzip数据格式使用与DeflateStream类相同的算法,但可以扩展为使用其他压缩格式。该格式很容易以专利未涵盖的方式实施。从.NET Framework 4.5开始,DeflateStream类使用zlib库进行压缩。因此,与.NET Framework的早期版本相比,它提供了更好的压缩算法,并且在大多数情况下,提供了较小的压缩文件。

GZipStream使用的一般流程如下:

打开一个现有的文件

打开/创建输出文件

创建GZipStream对象

逐字节读源文件,并把它传递到GZipStream

使用GZipStream写入到输出文件流

代码实现

1、压缩字符串

/// <summary>
        /// 壓縮字串,回傳 Base64 結果
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ZipText(string text)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(text);
            return ZipText(inputBytes);
        }

        public static string ZipText(byte[] inputBytes)
        {
            using (MemoryStream outputStream = new MemoryStream())
            {
                using (GZipStream gs = new GZipStream(outputStream, CompressionMode.Compress))
                {
                    gs.Write(inputBytes, 0, inputBytes.Length);
                }

                byte[] outputBytes = outputStream.ToArray();
                string result = Convert.ToBase64String(outputBytes);
                return result;
            }
        }

2、解压缩字符串

/// <summary>
        /// 解壓縮字串
        /// </summary>
        /// <param name="zippedText"></param>
        /// <returns></returns>
        public static string UnzipZippedText(string zippedText)
        {
            if (String.IsNullOrEmpty(zippedText))
            {
                return String.Empty;
            }
            string unzipedText = null;
            try
            {
                byte[] buffer = Convert.FromBase64String(zippedText);
                MemoryStream ms = new MemoryStream(buffer);
                GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress);

                using (StreamReader streamReader = new StreamReader(zipStream))
                {
                    unzipedText = streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                unzipedText = String.Empty;
            }

            return unzipedText;
        }

运行结果测试,源文件经过压缩大小只有120字节,而解压后,源文件与解压后txt的大小一致

9d91e69a1057e8652b276aa0b314a2ba.png

技术群:添加小编微信并备注进群

小编微信:mm1552923   

公众号:dotNet编程大全  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,可以使用 GZipStream 类轻松压缩字符串。以下是示例代码: ```csharp using System; using System.IO; using System.IO.Compression; class Program { static void Main(string[] args) { string originalString = "This is the original string to be compressed."; // 压缩字符串 byte[] compressedBytes; using (MemoryStream ms = new MemoryStream()) { using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress)) { using (StreamWriter writer = new StreamWriter(gzip)) { writer.Write(originalString); } } compressedBytes = ms.ToArray(); } // 将压缩后的字节数组转换回字符串 string compressedString = Convert.ToBase64String(compressedBytes); Console.WriteLine("Original string length: " + originalString.Length); Console.WriteLine("Compressed string length: " + compressedString.Length); } } ``` 在上面的代码中,我们使用 GZipStream 类将原始字符串压缩为字节数组,然后将字节数组转换为 Base64 编码的字符串。可以看到,压缩后的字符串长度很短,这意味着我们可以使用更少的空间来存储数据。 如果需要解压缩字符串,可以使用类似以下的代码: ```csharp using System; using System.IO; using System.IO.Compression; class Program { static void Main(string[] args) { string compressedString = "H4sIAAAAAAAAALvJyCxWAKtLAwAAAA=="; // 将压缩后的字符串转换为字节数组 byte[] compressedBytes = Convert.FromBase64String(compressedString); // 解压缩字节数组并转换为原始字符串 string originalString; using (MemoryStream ms = new MemoryStream(compressedBytes)) { using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress)) { using (StreamReader reader = new StreamReader(gzip)) { originalString = reader.ReadToEnd(); } } } Console.WriteLine("Original string: " + originalString); } } ``` 在上面的代码中,我们使用 GZipStream 类将压缩后的字节数组解压缩为原始字符串。需要注意的是,解压缩后的字符串可能包含不可见字符,因此建议使用 Base64 编码来转换压缩后的字节数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值