当前位置: 移动技术网 > IT编程>开发语言>c# > C# 使用SharpZipLib生成压缩包的实例代码

C# 使用SharpZipLib生成压缩包的实例代码

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文通过一个简单的小例子简述sharpziplib压缩文件的常规用法,仅供学习分享使用,如有不足之处,还请指正。 什么是sharpziplib ? sharpz

本文通过一个简单的小例子简述sharpziplib压缩文件的常规用法,仅供学习分享使用,如有不足之处,还请指正。

什么是sharpziplib ?

sharpziplib是一个c#的类库,主要用来解压缩zip,gzip,bzip2,tar等格式,是以托管程序集的方式实现,可以方便的应用于其他的项目之中。

在工程中引用sharpziplib

在项目中,点击项目名称右键-->管理nuget程序包,打开nuget包管理器窗口,进行搜索下载即可,如下图所示:

sharpziplib的关键类结构图

如下所示:

涉及知识点:

•zipoutputstream 压缩输出流,将文件一个接一个的写入压缩文档,此类不是线程安全的。
•putnextentry 开始一个新的zip条目,zipoutputstream中的方法。
•zipentry 一个zip文件中的条目,可以理解为压缩包里面的一个文件夹/文件。
•zipinputstream 解压缩输出流,从压缩包中一个接一个的读出文档。
•getnextentry 读出zip条目,zipinputstream中的方法。

示例效果图:

关于解压缩小例子的示例效果图,如下:

核心代码

using icsharpcode.sharpziplib.checksum;
using icsharpcode.sharpziplib.zip;
using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.text;
using system.threading.tasks;
namespace demozip
{
  class ziphelper
  {
    private string rootpath = string.empty;
    #region 压缩 
    /// <summary>  
    /// 递归压缩文件夹的内部方法  
    /// </summary>  
    /// <param name="foldertozip">要压缩的文件夹路径</param>  
    /// <param name="zipstream">压缩输出流</param>  
    /// <param name="parentfoldername">此文件夹的上级文件夹</param>  
    /// <returns></returns>  
    private bool zipdirectory(string foldertozip, zipoutputstream zipstream, string parentfoldername)
    {
      bool result = true;
      string[] folders, files;
      zipentry ent = null;
      filestream fs = null;
      crc32 crc = new crc32();
      try
      {
        string entname = foldertozip.replace(this.rootpath, string.empty)+"/";
        //path.combine(parentfoldername, path.getfilename(foldertozip) + "/")
        ent = new zipentry(entname);
        zipstream.putnextentry(ent);
        zipstream.flush();
        files = directory.getfiles(foldertozip);
        foreach (string file in files)
        {
          fs = file.openread(file);
          byte[] buffer = new byte[fs.length];
          fs.read(buffer, 0, buffer.length);
          ent = new zipentry(entname + path.getfilename(file));
          ent.datetime = datetime.now;
          ent.size = fs.length;
          fs.close();
          crc.reset();
          crc.update(buffer);
          ent.crc = crc.value;
          zipstream.putnextentry(ent);
          zipstream.write(buffer, 0, buffer.length);
        }
      }
      catch
      {
        result = false;
      }
      finally
      {
        if (fs != null)
        {
          fs.close();
          fs.dispose();
        }
        if (ent != null)
        {
          ent = null;
        }
        gc.collect();
        gc.collect(1);
      }
      folders = directory.getdirectories(foldertozip);
      foreach (string folder in folders)
        if (!zipdirectory(folder, zipstream, foldertozip))
          return false;
      return result;
    }
    /// <summary>  
    /// 压缩文件夹  
    /// </summary>  
    /// <param name="foldertozip">要压缩的文件夹路径</param>  
    /// <param name="zipedfile">压缩文件完整路径</param>  
    /// <param name="password">密码</param>  
    /// <returns>是否压缩成功</returns>  
    public bool zipdirectory(string foldertozip, string zipedfile, string password)
    {
      bool result = false;
      if (!directory.exists(foldertozip))
        return result;
      zipoutputstream zipstream = new zipoutputstream(file.create(zipedfile));
      zipstream.setlevel(6);
      if (!string.isnullorempty(password)) zipstream.password = password;
      result = zipdirectory(foldertozip, zipstream, "");
      zipstream.finish();
      zipstream.close();
      return result;
    }
    /// <summary>  
    /// 压缩文件夹  
    /// </summary>  
    /// <param name="foldertozip">要压缩的文件夹路径</param>  
    /// <param name="zipedfile">压缩文件完整路径</param>  
    /// <returns>是否压缩成功</returns>  
    public bool zipdirectory(string foldertozip, string zipedfile)
    {
      bool result = zipdirectory(foldertozip, zipedfile, null);
      return result;
    }
    /// <summary>  
    /// 压缩文件  
    /// </summary>  
    /// <param name="filetozip">要压缩的文件全名</param>  
    /// <param name="zipedfile">压缩后的文件名</param>  
    /// <param name="password">密码</param>  
    /// <returns>压缩结果</returns>  
    public bool zipfile(string filetozip, string zipedfile, string password)
    {
      bool result = true;
      zipoutputstream zipstream = null;
      filestream fs = null;
      zipentry ent = null;
      if (!file.exists(filetozip))
        return false;
      try
      {
        fs = file.openread(filetozip);
        byte[] buffer = new byte[fs.length];
        fs.read(buffer, 0, buffer.length);
        fs.close();
        fs = file.create(zipedfile);
        zipstream = new zipoutputstream(fs);
        if (!string.isnullorempty(password)) zipstream.password = password;
        ent = new zipentry(path.getfilename(filetozip));
        zipstream.putnextentry(ent);
        zipstream.setlevel(6);
        zipstream.write(buffer, 0, buffer.length);
      }
      catch
      {
        result = false;
      }
      finally
      {
        if (zipstream != null)
        {
          zipstream.finish();
          zipstream.close();
        }
        if (ent != null)
        {
          ent = null;
        }
        if (fs != null)
        {
          fs.close();
          fs.dispose();
        }
      }
      gc.collect();
      gc.collect(1);
      return result;
    }
    /// <summary>  
    /// 压缩文件  
    /// </summary>  
    /// <param name="filetozip">要压缩的文件全名</param>  
    /// <param name="zipedfile">压缩后的文件名</param>  
    /// <returns>压缩结果</returns>  
    public bool zipfile(string filetozip, string zipedfile)
    {
      bool result = zipfile(filetozip, zipedfile, null);
      return result;
    }
    /// <summary>  
    /// 压缩文件或文件夹  
    /// </summary>  
    /// <param name="filetozip">要压缩的路径</param>  
    /// <param name="zipedfile">压缩后的文件名</param>  
    /// <param name="password">密码</param>  
    /// <returns>压缩结果</returns>  
    public bool zip(string filetozip, string zipedfile, string password)
    {
      bool result = false;
      if (directory.exists(filetozip))
      {
        this.rootpath = path.getdirectoryname(filetozip);
        result = zipdirectory(filetozip, zipedfile, password);
      }
      else if (file.exists(filetozip))
      {
        this.rootpath = path.getdirectoryname(filetozip);
        result = zipfile(filetozip, zipedfile, password);
      }
      return result;
    }
    /// <summary>  
    /// 压缩文件或文件夹  
    /// </summary>  
    /// <param name="filetozip">要压缩的路径</param>  
    /// <param name="zipedfile">压缩后的文件名</param>  
    /// <returns>压缩结果</returns>  
    public bool zip(string filetozip, string zipedfile)
    {
      bool result = zip(filetozip, zipedfile, null);
      return result;
    }
    #endregion
    #region 解压 
    /// <summary>  
    /// 解压功能(解压压缩文件到指定目录)  
    /// </summary>  
    /// <param name="filetounzip">待解压的文件</param>  
    /// <param name="zipedfolder">指定解压目标目录</param>  
    /// <param name="password">密码</param>  
    /// <returns>解压结果</returns>  
    public bool unzip(string filetounzip, string zipedfolder, string password)
    {
      bool result = true;
      filestream fs = null;
      zipinputstream zipstream = null;
      zipentry ent = null;
      string filename;
      if (!file.exists(filetounzip))
        return false;
      if (!directory.exists(zipedfolder))
        directory.createdirectory(zipedfolder);
      try
      {
        zipstream = new zipinputstream(file.openread(filetounzip));
        if (!string.isnullorempty(password)) zipstream.password = password;
        while ((ent = zipstream.getnextentry()) != null)
        {
          if (!string.isnullorempty(ent.name))
          {
            filename = path.combine(zipedfolder, ent.name);
            filename = filename.replace('/', '\\');//change by mr.hopegi  
            if (filename.endswith("\\"))
            {
              directory.createdirectory(filename);
              continue;
            }
            fs = file.create(filename);
            int size = 2048;
            byte[] data = new byte[size];
            while (true)
            {
              size = zipstream.read(data, 0, data.length);
              if (size > 0)
                fs.write(data, 0, data.length);
              else
                break;
            }
          }
        }
      }
      catch
      {
        result = false;
      }
      finally
      {
        if (fs != null)
        {
          fs.close();
          fs.dispose();
        }
        if (zipstream != null)
        {
          zipstream.close();
          zipstream.dispose();
        }
        if (ent != null)
        {
          ent = null;
        }
        gc.collect();
        gc.collect(1);
      }
      return result;
    }
    /// <summary>  
    /// 解压功能(解压压缩文件到指定目录)  
    /// </summary>  
    /// <param name="filetounzip">待解压的文件</param>  
    /// <param name="zipedfolder">指定解压目标目录</param>  
    /// <returns>解压结果</returns>  
    public bool unzip(string filetounzip, string zipedfolder)
    {
      bool result = unzip(filetounzip, zipedfolder, null);
      return result;
    }
    #endregion
  }
}

备注

关于生成压缩的方法还有很多,如通过命令行调用winrar的执行文件,sharpziplib只是方法之一。

关于sharpziplib的的api文档,可参看链接

总结

以上所述是小编给大家介绍的c# 使用sharpziplib生成压缩包的实例代码,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网