Zip加解压字符串

一、首先下载引用“ICSharpCode.SharpZipLib.dll”

 

二、字符串压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/// <summary>
       /// 将传入的二进制字符串资料以Zip算法解压缩
       /// </summary>
       /// <param name="zippedString">经GZip压缩后的二进制字符串</param>
       /// <returns>原始未压缩字符串</returns>
       public static string ZipDecompressString(this string zippedString)
       {
           if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
           {
               return "";
           }
           else
           {
               string dummyData = zippedString;
               dummyData = dummyData.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+").Replace("\"", "").Replace("\\n", "");
 
               //}
               byte[] b = Convert.FromBase64String(dummyData);
               using (MemoryStream from = new MemoryStream(b))
               using (ZipInputStream zip = new ZipInputStream(from))
               using (MemoryStream to = new MemoryStream())
               {
                   ZipEntry entry = zip.GetNextEntry();
                   byte[] buffer = new byte[1024];
                   int len = 0;
                   while ((len = zip.Read(buffer, 0, buffer.Length)) > 0)
                   {
                       to.Write(buffer, 0, len);
                   }
                   b = to.ToArray();
                   return Encoding.UTF8.GetString(b);
               }
           }
       }

 

三、压缩字符串解压

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/// <summary>
        /// 将传入字符串以Zip算法压缩后,返回utf-8格式Base64编码字符
        /// </summary>
        /// <param name="rawString">需要压缩的字符串</param>
        /// <returns>压缩后的Base64编码的字符串</returns>
        public static string ZipCompressString(this string rawString)
        {
            if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString);
                using (MemoryStream to = new MemoryStream())
                using (ZipOutputStream zip = new ZipOutputStream(to))
                {
                    ZipEntry entry = new ZipEntry("ToBase64String");
                    zip.PutNextEntry(entry);
 
                    zip.Write(rawData, 0, rawData.Length);
                    zip.CloseEntry();  // 必须,否则报不可预料的压缩文件末端
                    zip.Finish();      // 必须,否则报这个压缩文件格式未知或者数据已经被损坏
                    return Convert.ToBase64String(to.ToArray());
                }
            }
        }

  

posted @   遨游天际  阅读(246)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示