项目中使用 Velocity 将模板和生成的动态内容(HTML、XML等)合并保存到redis数据库中,考虑到压缩的文件容量会比较小,方便传输而且存储所使用的空间也会比较小,所以要压缩一下,读取的时候也要解压,所以就用到了SharpZipLib。SharpZipLib是一个完全用c#为. net平台编写的Zip、GZip、Tar和BZip2库。官网代码下载https://github.com/icsharpcode/SharpZipLib。如果要使用SharpZipLib,我们可以直接下载源码引入项目,也可以下载SharpZLib.dll。SharpZLib.dll可以从网上下载也可以通过代码自己生成dill。

  压缩分为无损压缩和有损压缩,有损压缩指的是压缩之后就无法完整还原原始信息,但是压缩率可以很高,主要应用于视频、话音等数据的压缩,如果没必要完整还原信息,可以使用有损压缩,仅仅损失了一点信息,很难察觉;无损压缩则用于文件等等必须完整还原信息的场合,常见的无损压缩包括Zip、GZip、RAR、Tar、BZip2等。

一、如何使用SharpZipLib

  1、项目中引用SharpZLib.dll

  2、本项目中,单独写了一个ZipHelper类,用来使用SharpZipLib中封装的压缩方式。zipHelper类时可以作为使用Zip、Tar、GZip、Lzw、BZip2压缩方式的入口。直接上ZipHelper类的代码吧   

  

using SharpZipLib.BZip2;
using SharpZipLib.Checksum;
using SharpZipLib.Core.Exceptions;
using SharpZipLib.GZip;
using SharpZipLib.Tar;
using SharpZipLib.Zip;
using SharpZipLib.Zip.Compression;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace SharpZipLibExample
{
    /// <summary>
    /// 网上关于压缩的只是很多
    /// https://www.cnblogs.com/kissdodog/p/3525295.html
    /// </summary>
    public class ZipHelper
    {
        ;
        #region Zip
        /// <summary>
        /// Zip文件压缩
        /// ZipOutputStream:相当于一个压缩包;
        /// ZipEntry:相当于压缩包里的一个文件;
        /// 以上两个类是SharpZipLib的主类。
        /// </summary>
        /// <param name="sourceFileLists"></param>
        /// <param name="descFile">压缩文件保存的目录</param>
        /// <param name="compression">压缩级别</param>
        public static void ZipCompress(List<string> sourceFileLists, string descFile, int compression)
        {
             || compression > )
            {
                throw new ArgumentException("错误的压缩级别");
            }
            if (!Directory.Exists(new FileInfo(descFile).Directory.ToString()))
            {
                throw new ArgumentException("保存目录不存在");
            }
            foreach (string c in sourceFileLists)
            {
                if (!File.Exists(c))
                {
                    throw new ArgumentException(string.Format("文件{0} 不存在!", c));
                }
            }
            Crc32 crc32 = new Crc32();
            using (ZipOutputStream stream = new ZipOutputStream(File.Create(descFile)))
            {
                stream.SetLevel(compression);
                ZipEntry entry;
                ; i < sourceFileLists.Count; i++)
                {
                    entry = new ZipEntry(Path.GetFileName(sourceFileLists[i]));
                    entry.DateTime = DateTime.Now;
                    using (FileStream fs = File.OpenRead(sourceFileLists[i]))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, , buffer.Length);
                        entry.Size = fs.Length;
                        crc32.Reset();
                        crc32.Update(buffer);
                        entry.Crc = crc32.Value;
                        stream.PutNextEntry(entry);
                        stream.Write(buffer, , buffer.Length);
                    }
                    stream.CloseEntry();
                }

            }
        }
        /// <summary>
        /// unZip文件解压缩
        /// </summary>
        /// <param name="sourceFile">要解压的文件</param>
        /// <param name="path">要解压到的目录</param>
        public static void ZipDeCompress(string sourceFile, string path)
        {
            if (!File.Exists(sourceFile))
            {
                throw new ArgumentException("要解压的文件不存在。");
            }
            if (!Directory.Exists(path))
            {
                throw new ArgumentException("要解压到的目录不存在!");
            }
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourceFile)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string fileName = System.IO.Path.GetFileName(theEntry.Name);
                    if (fileName != string.Empty)
                    {
                        using (FileStream streamWriter = File.Create(path + @"\" + theEntry.Name))
                        {
                            ;
                            ];
                            while (true)
                            {
                                size = s.Read(data, , data.Length);
                                )
                                {
                                    streamWriter.Write(data, , size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 字符串压缩
        /// </summary>
        /// <param name="text">待压缩的字符串</param>
        /// <returns>已压缩的字符串</returns>
        public static string ZipCompress(string text)
        {
            string result = string.Empty;
            byte[] data = Encoding.UTF8.GetBytes(text);
            byte[] dData = ZipCompress(data);
            result = Convert.ToBase64String(dData);
            Array.Clear(dData, , dData.Length);
            return result;
        }
        /// <summary>
        /// 字符串解压
        /// </summary>
        /// <param name="text">待解压的字符串</param>
        /// <returns>已解压的字符串</returns>
        public static string ZipDeCompress(string text)
        {
            string result = string.Empty;
            byte[] data = Convert.FromBase64String(text);
            byte[] dData = ZipDeCompress(data);
            result = Encoding.UTF8.GetString(dData);
            Array.Clear(dData,,dData.Length);
            return result;
        }
        /// <summary>
        /// 字节数组压缩
        /// </summary>
        /// <param name="data">待压缩的字节数组</param>
        /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
        /// <returns>已压缩的字节数组</returns>
        public static byte[] ZipCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            Deflater f = new Deflater(Deflater.BEST_COMPRESSION);
            f.SetInput(data);
            f.Finish();
            ;
            using (MemoryStream o=new MemoryStream(data.Length))
            {
                byte[] buffer = new byte[BUFFER_LENGTH];
                while (!f.IsFinished)
                {
                    count = f.Deflate(buffer);
                    o.Write(buffer,,count);
                }
                bytes = o.ToArray();
            }
            if (isClearData)
            {
                Array.Clear(data,,data.Length);
            }
            return bytes;
        }
        /// <summary>
        /// 字节数组解压缩
        /// </summary>
        /// <param name="data">待解压缩的字节数组</param>
        /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
        /// <returns>已解压的字节数组</returns>
        public static byte[] ZipDeCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            Inflater f = new Inflater();
            f.SetInput(data);
            ;
            using (MemoryStream o=new MemoryStream(data.Length))
            {
                byte[] buffer = new byte[BUFFER_LENGTH];
                while (!f.IsFinished)
                {
                    count = f.Inflate(buffer);
                    o.Write(buffer,,count);
                }
                bytes = o.ToArray();
            }
            if (isClearData)
            {
                Array.Clear(data,,count);
            }
            return bytes;
        }
        #endregion

        #region GZip
        /// <summary>
        /// 压缩字符串
        /// </summary>
        /// <param name="text">待压缩的字符串组</param>
        /// <returns>已压缩的字符串</returns>
        public static string GZipCompress(string text)
        {
            string result = string.Empty;
            byte[] data = Encoding.UTF8.GetBytes(text);
            byte[] cData = GZipCompress(data);
            result = Convert.ToBase64String(cData);
            Array.Clear(cData, , cData.Length);
            return result;
        }
        /// <summary>
        /// 解压缩字符串
        /// </summary>
        /// <param name="text">待解压缩的字符串</param>
        /// <returns>已解压缩的字符串</returns>
        public static string GZipDeCompress(string text)
        {
            string result = string.Empty;
            byte[] data = Convert.FromBase64String(text);
            byte[] cData = GZipDeCompress(data);
            result = Encoding.UTF8.GetString(cData);
            Array.Clear(cData, , cData.Length);
            return result;
        }
        /// <summary>
        /// 压缩字节数组
        /// </summary>
        /// <param name="data">待压缩的字节数组</param>
        /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
        /// <returns>已压缩的字节数组</returns>
        public static byte[] GZipCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            try
            {
                using (MemoryStream o = new MemoryStream())
                {
                    using (Stream s = new GZipOutputStream(o))
                    {
                        s.Write(data, , data.Length);
                        s.Flush();
                    }
                    bytes = o.ToArray();
                }
            }
            catch (SharpZipBaseException)
            {
            }
            catch (IndexOutOfRangeException)
            {
            }
            if (isClearData)
                Array.Clear(data, , data.Length);
            return bytes;
        }

        /// <summary>
        /// 解压缩字节数组
        /// </summary>
        /// <param name="data">待解压缩的字节数组</param>
        /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
        /// <returns>已解压的字节数组</returns>
        public static byte[] GZipDeCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            try
            {
                using (MemoryStream o = new MemoryStream())
                {
                    using (MemoryStream ms = new MemoryStream(data))
                    {
                        using (Stream s = new GZipInputStream(ms))
                        {
                            s.Flush();
                            ;
                            byte[] buffer = new byte[BUFFER_LENGTH];
                            , buffer.Length)) > )
                            {
                                o.Write(buffer, , size);
                            }
                        }
                    }
                    bytes = o.ToArray();
                }
            }
            catch (SharpZipBaseException)
            {
            }
            catch (IndexOutOfRangeException)
            {
            }
            if (isClearData)
                Array.Clear(data, , data.Length);
            return bytes;
        }
        #endregion

        #region Tar
        /// <summary>
        /// 压缩字符串
        /// </summary>
        /// <param name="text">待压缩的字符串组</param>
        /// <returns>已压缩的字符串</returns>
        public static string TarCompress(string text)
        {
            string result = null;
            byte[] data = Encoding.UTF8.GetBytes(text);
            byte[] dData = TarCompress(data);
            result = Convert.ToBase64String(dData);
            Array.Clear(dData, , dData.Length);
            return result;
        }
        /// <summary>
        /// 解压缩字符串
        /// </summary>
        /// <param name="text">待解压缩的字符串</param>
        /// <returns>已解压的字符串</returns>
        public static string TarDeCompress(string text)
        {
            string result = null;
            byte[] data = Convert.FromBase64String(text);
            byte[] dData = TarDeCompress(data);
            result = Encoding.UTF8.GetString(dData);
            Array.Clear(dData, , dData.Length);
            return result;
        }
        /// <summary>
        /// 压缩字节数组
        /// </summary>
        /// <param name="data">待压缩的字节数组</param>
        /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
        /// <returns>已压缩的字节数组</returns>
        public static byte[] TarCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            using (MemoryStream o = new MemoryStream())
            {
                using (Stream s = new TarOutputStream(o))
                {
                    s.Write(data, , data.Length);
                    s.Flush();
                }
                bytes = o.ToArray();
            }
            if (isClearData)
                Array.Clear(data, , data.Length);
            return bytes;
        }
        /// <summary>
        /// 解压缩字节数组
        /// </summary>
        /// <param name="data">待解压缩的字节数组</param>
        /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
        /// <returns>已解压的字节数组</returns>
        public static byte[] TarDeCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            using (MemoryStream o = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(data))
                {
                    using (Stream s = new TarInputStream(ms))
                    {
                        s.Flush();
                        ;
                        byte[] buffer = new byte[BUFFER_LENGTH];
                        , buffer.Length)) > )
                        {
                            o.Write(buffer, , size);
                        }
                    }
                }
                bytes = o.ToArray();
            }
            if (isClearData)
                Array.Clear(data, , data.Length);
            return bytes;
        }
        #endregion

        #region BZip
        /// <summary>
        /// 压缩字符串
        /// </summary>
        /// <param name="text">待压缩的字符串组</param>
        /// <returns>已压缩的字符串</returns>
        public static string BZipCompress(string text)
        {
            string result = null;
            byte[] data = Encoding.UTF8.GetBytes(text);
            byte[] dData = BZipCompress(data);
            result = Convert.ToBase64String(dData);
            Array.Clear(dData, , dData.Length);
            return result;
        }
        /// <summary>
        /// 解压缩字符串
        /// </summary>
        /// <param name="text">待解压缩的字符串</param>
        /// <returns>已解压的字符串</returns>
        public static string BZipDeCompress(string text)
        {
            string result = null;
            byte[] data = Convert.FromBase64String(text);
            byte[] dData = BZipDeCompress(data);
            result = Encoding.UTF8.GetString(dData);
            Array.Clear(dData, , dData.Length);
            return result;
        }
        /// <summary>
        /// 压缩字节数组
        /// </summary>
        /// <param name="data">待压缩的字节数组</param>
        /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
        /// <returns>已压缩的字节数组</returns>
        public static byte[] BZipCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            using (MemoryStream o = new MemoryStream())
            {
                using (Stream s = new BZip2OutputStream(o))
                {
                    s.Write(data, , data.Length);
                    s.Flush();
                }
                bytes = o.ToArray();
            }
            if (isClearData)
                Array.Clear(data, , data.Length);
            return bytes;
        }
        /// <summary>
        /// 解压缩字节数组
        /// </summary>
        /// <param name="data">待解压缩的字节数组</param>
        /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
        /// <returns>已解压的字节数组</returns>
        public static byte[] BZipDeCompress(byte[] data, bool isClearData = true)
        {
            byte[] bytes = null;
            using (MemoryStream o = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(data))
                {
                    using (Stream s = new BZip2InputStream(ms))
                    {
                        s.Flush();
                        ;
                        byte[] buffer = new byte[BUFFER_LENGTH];
                        , buffer.Length)) > )
                        {
                            o.Write(buffer, , size);
                        }
                    }
                }
                bytes = o.ToArray();
            }
            if (isClearData)
                Array.Clear(data, , data.Length);
            return bytes;
        }
        #endregion
    }
}

  3、程序入口main  

  

using System;
using System.Linq;
using System.Text;

namespace SharpZipLibExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string strContent = "夜,结束了一天的喧嚣后安静下来,伴随着远处路灯那微弱的光。风,毫无预兆地席卷整片旷野,撩动人的思绪万千。星,遥遥地挂在天空之中,闪烁着它那微微星光,不如阳光般灿烂却如花儿般如痴如醉。";
            Console.WriteLine("原文:{0}",strContent);
            #region 压缩
            string compressContent = ZipHelper.BZipCompress(strContent);
            Console.WriteLine("压缩后的内容:{0};压缩后的内容大小:{1}", compressContent, Convert.FromBase64String(compressContent).Count().ToString());
            #endregion

            #region 解压缩
            strContent = ZipHelper.BZipDeCompress(compressContent);
            Console.WriteLine("解压缩后的内容:{0};解压缩后的内容大小:{1}", strContent,Encoding.UTF8.GetBytes(strContent).Count().ToString());
            #endregion
            Console.ReadKey();
        }
    }
}

完整的Demo下载地址https://download.csdn.net/download/u011392711/10827889

 

SharpZipLib压缩解压的使用的更多相关文章

  1. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  2. SharpZipLib压缩解压

    一.介绍 SharpZipLib是一个完全由C#编写的ZIP,GZIP,Tar和BZIP2 Library,可以方便的支持这几种格式的压缩和解压缩. https://github.com/icshar ...

  3. ICSharpCode.SharpZipLib压缩解压

    一.使用ICSharpCode.SharpZipLib.dll: 下载地址 http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.asp ...

  4. C#基础知识之SharpZipLib压缩解压的使用

    项目中使用 Velocity 将模板和生成的动态内容(HTML.XML等)合并保存到redis数据库中,考虑到压缩的文件容量会比较小,方便传输而且存储所使用的空间也会比较小,所以要压缩一下,读取的时候 ...

  5. C#使用SharpZipLib压缩解压文件

    #region 加压解压方法 /// <summary> /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// </summary> // ...

  6. 通过SharpZipLib来压缩解压文件

    在项目开发中,一些比较常用的功能就是压缩解压文件了,其实类似的方法有许多 ,现将通过第三方类库SharpZipLib来压缩解压文件的方法介绍如下,主要目的是方便以后自己阅读,当然可以帮到有需要的朋友更 ...

  7. 使用SharpZIpLib写的压缩解压操作类

    使用SharpZIpLib写的压缩解压操作类,已测试. public class ZipHelper { /// <summary> /// 压缩文件 /// </summary&g ...

  8. (转载)C#压缩解压zip 文件

    转载之: C#压缩解压zip 文件 - 大气象 - 博客园http://www.cnblogs.com/greatverve/archive/2011/12/27/csharp-zip.html C# ...

  9. 使用C#压缩解压rar和zip格式文件

    为了便于文件在网络中的传输和保存,通常将文件进行压缩操作,常用的压缩格式有rar.zip和7z,本文将介绍在C#中如何对这几种类型的文件进行压缩和解压,并提供一些在C#中解压缩文件的开源库. 在C#. ...

随机推荐

  1. missing requires of libmysqlclient.so.18()(64bit)

    错误提示安装依赖的库文件没有找到: libmysqlclient.so.18()(64bit)   解决方法是这样的:   安装mysql-community-libs-compat-5.7.18-1 ...

  2. kubernetes 安装备注

    一.安装环境 阿里云:centos 7.3 master节点:外网IP(116.62.205.90).内网IP(172.16.223.200) node节点:外网IP(116.62.212.174). ...

  3. MYSQL的group by笔记

    对应的表数据如下 现在的需求是要找出dcid为9951,9957,9064共同拥有的good_code. 第一种方案是 SELECT a.good_code FROM ( SELECT good_co ...

  4. CentOS7 安装mysql 5.7

    一.安装准备 检查系统中是否安装了mysqlrpm -qa|grep mysql如果有安装mysql,则需要先卸载之前安装的mysqlyum -y remove mysql然后再查看mysql是否都卸 ...

  5. Android 性能测试优质实践汇总

    这两天把testerhome上的关于Android 性能测试的精品文章看了一遍,很有收获,学习到了Android 性能测试该关注的一些细节.我所说的“精品”是指对我自己有启发的文章,可以被自己运用起来 ...

  6. Flink从入门到放弃(入门篇1)-Flink是什么

    戳更多文章: 1-Flink入门 2-本地环境搭建&构建第一个Flink应用 3-DataSet API 4-DataSteam API 5-集群部署 6-分布式缓存 7-重启策略 8-Fli ...

  7. Linux运维企业架构实战系列

    Linux运维企业架构项目实战系列 项目实战1-LNMP的搭建.nginx的ssl加密.权限控制的实现 项目实战2-LVS.nginx实现负载均衡系列 2.1 项目实战2.1-实现基于LVS负载均衡集 ...

  8. 痞子衡嵌入式:飞思卡尔Kinetis系列MCU开发那些事 - 索引

    大家好,我是痞子衡,是正经搞技术的痞子.本系列痞子衡给大家介绍的是飞思卡尔Kinetis系列微控制器相关知识. 飞思卡尔半导体(现恩智浦半导体)于2010年开始推出的Kinetis系列昭示着ARM C ...

  9. 【憩园】C#并发编程之异步编程(三)

      写在前面 本篇是异步编程系列的第三篇,本来计划第三篇的内容是介绍异步编程中常用的几个方法,但是前两篇写出来后,身边的朋友总是会有其他问题,所以决定再续写一篇,作为异步编程(一)和异步编程(二)的补 ...

  10. C#实现.ini文件读写操作

    1.ini文件是什么?        见百度百科:https://baike.baidu.com/item/ini%E6%96%87%E4%BB%B6/9718973?fr=aladdin 2.C#语 ...