栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#中ZipHelper 压缩和解压帮助类

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#中ZipHelper 压缩和解压帮助类

关于本文档的说明

  本文档基于ICSharpCode.SharpZipLib.dll的封装,常用的解压和压缩方法都已经涵盖在内,都是经过项目实战积累下来的

  欢迎传播分享,必须保持原作者的信息,但禁止将该文档直接用于商业盈利。

  本人自从几年前走上编程之路,一直致力于收集和总结出好用的框架和通用类库,不管是微软自己的还是第三方的只要实际项目中好用且可以解决实际问题那都会收集好,编写好文章和别人一起分享,这样自己学到了,别人也能学到知识,当今社会很需要知识的搬运工。

1.基本介绍

      由于项目中需要用到各种压缩将文件进行压缩下载,减少网络的带宽,所以压缩是一个非常常见的功能,对于压缩微软自己也提供了一些类库

微软自带压缩类ZipArchive类,适合NET frameWork4.5才可以使用
调用压缩软件命令执行压缩动作,这个就需要电脑本身安装压缩软件了
使用第三方的压缩dll文件,一般使用最多的是(ICSharpCode.SharpZipLib.dll),下载dll ICSharpCode.SharpZipLib.zip

2.实际项目

压缩单个文件,需要指定压缩等级
压缩单个文件夹,需要指定压缩等级
压缩多个文件或者多个文件夹
对压缩包进行加密【用的较少,实际情况也有】

2.1 压缩单个文件

写了两个方法,可以指定压缩等级,这样你的压缩包大小就不一样了

2.2 压缩单个文件夹

复制代码 代码如下:
public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = 9)

2.3 压缩多个文件或者文件夹

复制代码 代码如下:
public bool ZipManyFilesOrDictorys(IEnumerable folderOrFileList, string zipedFile, string password)

2.4 对压缩包进行加密

复制代码 代码如下:
public bool ZipManyFilesOrDictorys(IEnumerable folderOrFileList, string zipedFile, string password)

2.5 直接解压,无需密码

public void UnZip(string zipFilePath, string unZipDir)


3.演示图 

 

3.ZipHelper源码

//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2016 , ZTO , Ltd .
//-------------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace ZTO.PicTest.Utilities
{
  using ICSharpCode.SharpZipLib.Checksums;
  using ICSharpCode.SharpZipLib.Zip;

  /// 
  /// Zip压缩帮助类
  ///
  /// 修改纪录
  ///
  ///    2015-09-16 版本:1.0 YangHengLian 创建主键,注意命名空间的排序。
  ///   2016-5-7 YangHengLian增加了可以支持多个文件或者多个文件夹打包成一个zip文件
  /// 
  /// 版本:1.0
  ///
  /// 
  ///    YangHengLian
  ///    2015-09-16
  /// 
  /// 
  public class ZipHelper
  {
    /// 
    /// 压缩文件夹
    /// 
    /// 
    /// 
    /// 压缩率0(无压缩)9(压缩率最高)
    public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = 9)
    {
      if (Path.GetExtension(zipedFileName) != ".zip")
      {
 zipedFileName = zipedFileName + ".zip";
      }
      using (var zipoutputstream = new ZipOutputStream(File.Create(zipedFileName)))
      {
 zipoutputstream.SetLevel(compressionLevel);
 Crc32 crc = new Crc32();
 Hashtable fileList = GetAllFies(dirToZip);
 foreach (DictionaryEntry item in fileList)
 {
   FileStream fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
   byte[] buffer = new byte[fs.Length];
   fs.Read(buffer, 0, buffer.Length);
   // ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(dirToZip.Length + 1));
   ZipEntry entry = new ZipEntry(Path.GetFileName(item.Key.ToString()))
     {
DateTime = (DateTime) item.Value,
Size = fs.Length
     };
   fs.Close();
   crc.Reset();
   crc.Update(buffer);
   entry.Crc = crc.Value;
   zipoutputstream.PutNextEntry(entry);
   zipoutputstream.Write(buffer, 0, buffer.Length);
 }
      }
    }

    ///  
    /// 获取所有文件 
    ///  
    ///  
    public Hashtable GetAllFies(string dir)
    {
      Hashtable filesList = new Hashtable();
      DirectoryInfo fileDire = new DirectoryInfo(dir);
      if (!fileDire.Exists)
      {
 throw new FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
      }

      GetAllDirFiles(fileDire, filesList);
      GetAllDirsFiles(fileDire.GetDirectories(), filesList);
      return filesList;
    }

    ///  
    /// 获取一个文件夹下的所有文件夹里的文件 
    ///  
    ///  
    ///  
    public void GetAllDirsFiles(IEnumerable dirs, Hashtable filesList)
    {
      foreach (DirectoryInfo dir in dirs)
      {
 foreach (FileInfo file in dir.GetFiles("*.*"))
 {
   filesList.Add(file.FullName, file.LastWriteTime);
 }
 GetAllDirsFiles(dir.GetDirectories(), filesList);
      }
    }

    ///  
    /// 获取一个文件夹下的文件 
    ///  
    /// 目录名称
    /// 文件列表HastTable 
    public static void GetAllDirFiles(DirectoryInfo dir, Hashtable filesList)
    {
      foreach (FileInfo file in dir.GetFiles("*.*"))
      {
 filesList.Add(file.FullName, file.LastWriteTime);
      }
    }

    ///  
    /// 功能:解压zip格式的文件。 
    ///  
    /// 压缩文件路径 
    /// 解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 
    /// 解压是否成功 
    public void UnZip(string zipFilePath, string unZipDir)
    {
      if (zipFilePath == string.Empty)
      {
 throw new Exception("压缩文件不能为空!");
      }
      if (!File.Exists(zipFilePath))
      {
 throw new FileNotFoundException("压缩文件不存在!");
      }
      //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 
      if (unZipDir == string.Empty)
 unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
      if (!unZipDir.EndsWith("/"))
 unZipDir += "/";
      if (!Directory.Exists(unZipDir))
 Directory.CreateDirectory(unZipDir);

      using (var s = new ZipInputStream(File.OpenRead(zipFilePath)))
      {

 ZipEntry theEntry;
 while ((theEntry = s.GetNextEntry()) != null)
 {
   string directoryName = Path.GetDirectoryName(theEntry.Name);
   string fileName = Path.GetFileName(theEntry.Name);
   if (!string.IsNullOrEmpty(directoryName))
   {
     Directory.CreateDirectory(unZipDir + directoryName);
   }
   if (directoryName != null && !directoryName.EndsWith("/"))
   {
   }
   if (fileName != String.Empty)
   {
     using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
     {

int size;
byte[] data = new byte[2048];
while (true)
{
  size = s.Read(data, 0, data.Length);
  if (size > 0)
  {
    streamWriter.Write(data, 0, size);
  }
  else
  {
    break;
  }
}
     }
   }
 }
      }
    }

    /// 
    /// 压缩单个文件
    /// 
    /// 被压缩的文件名称(包含文件路径),文件的全路径
    /// 压缩后的文件名称(包含文件路径),保存的文件名称
    /// 压缩率0(无压缩)到 9(压缩率最高)
    public void ZipFile(string filePath, string zipedFileName, int compressionLevel = 9)
    {
      // 如果文件没有找到,则报错 
      if (!File.Exists(filePath))
      {
 throw new FileNotFoundException("文件:" + filePath + "没有找到!");
      }
      // 如果压缩后名字为空就默认使用源文件名称作为压缩文件名称
      if (string.IsNullOrEmpty(zipedFileName))
      {
 string oldValue = Path.GetFileName(filePath);
 if (oldValue != null)
 {
   zipedFileName = filePath.Replace(oldValue, "") + Path.GetFileNameWithoutExtension(filePath) + ".zip";
 }
      }
      // 如果压缩后的文件名称后缀名不是zip,就是加上zip,防止是一个乱码文件
      if (Path.GetExtension(zipedFileName) != ".zip")
      {
 zipedFileName = zipedFileName + ".zip";
      }
      // 如果指定位置目录不存在,创建该目录 C:UsersyhlDesktop大汉三通
      string zipedDir = zipedFileName.Substring(0, zipedFileName.LastIndexOf("\", StringComparison.Ordinal));
      if (!Directory.Exists(zipedDir))
      {
 Directory.CreateDirectory(zipedDir);
      }
      // 被压缩文件名称
      string filename = filePath.Substring(filePath.LastIndexOf("\", StringComparison.Ordinal) + 1);
      var streamToZip = new FileStream(filePath, FileMode.Open, FileAccess.Read);
      var zipFile = File.Create(zipedFileName);
      var zipStream = new ZipOutputStream(zipFile);
      var zipEntry = new ZipEntry(filename);
      zipStream.PutNextEntry(zipEntry);
      zipStream.SetLevel(compressionLevel);
      var buffer = new byte[2048];
      Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
      zipStream.Write(buffer, 0, size);
      try
      {
 while (size < streamToZip.Length)
 {
   int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
   zipStream.Write(buffer, 0, sizeRead);
   size += sizeRead;
 }
      }
      finally
      {
 zipStream.Finish();
 zipStream.Close();
 streamToZip.Close();
      }
    }

    ///  
    /// 压缩单个文件 
    ///  
    /// 要进行压缩的文件名,全路径 
    /// 压缩后生成的压缩文件名,全路径 
    public void ZipFile(string fileToZip, string zipedFile)
    {
      // 如果文件没有找到,则报错 
      if (!File.Exists(fileToZip))
      {
 throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
      }
      using (FileStream fileStream = File.OpenRead(fileToZip))
      {
 byte[] buffer = new byte[fileStream.Length];
 fileStream.Read(buffer, 0, buffer.Length);
 fileStream.Close();
 using (FileStream zipFile = File.Create(zipedFile))
 {
   using (ZipOutputStream zipOutputStream = new ZipOutputStream(zipFile))
   {
     // string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\") + 1);
     string fileName = Path.GetFileName(fileToZip);
     var zipEntry = new ZipEntry(fileName)
     {
DateTime = DateTime.Now,
IsUnicodeText = true
     };
     zipOutputStream.PutNextEntry(zipEntry);
     zipOutputStream.SetLevel(5);
     zipOutputStream.Write(buffer, 0, buffer.Length);
     zipOutputStream.Finish();
     zipOutputStream.Close();
   }
 }
      }
    }

    /// 
    /// 压缩多个目录或文件
    /// 
    /// 待压缩的文件夹或者文件,全路径格式,是一个集合
    /// 压缩后的文件名,全路径格式
    /// 压宿密码
    /// 
    public bool ZipManyFilesOrDictorys(IEnumerable folderOrFileList, string zipedFile, string password)
    {
      bool res = true;
      using (var s = new ZipOutputStream(File.Create(zipedFile)))
      {
 s.SetLevel(6);
 if (!string.IsNullOrEmpty(password))
 {
   s.Password = password;
 }
 foreach (string fileOrDir in folderOrFileList)
 {
   //是文件夹
   if (Directory.Exists(fileOrDir))
   {
     res = ZipFileDictory(fileOrDir, s, "");
   }
   else
   {
     //文件
     res = ZipFileWithStream(fileOrDir, s);
   }
 }
 s.Finish();
 s.Close();
 return res;
      }
    }

    /// 
    /// 带压缩流压缩单个文件
    /// 
    /// 要进行压缩的文件名
    /// 
    /// 
    private bool ZipFileWithStream(string fileToZip, ZipOutputStream zipStream)
    {
      //如果文件没有找到,则报错
      if (!File.Exists(fileToZip))
      {
 throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
      }
      //FileStream fs = null;
      FileStream zipFile = null;
      ZipEntry zipEntry = null;
      bool res = true;
      try
      {
 zipFile = File.OpenRead(fileToZip);
 byte[] buffer = new byte[zipFile.Length];
 zipFile.Read(buffer, 0, buffer.Length);
 zipFile.Close();
 zipEntry = new ZipEntry(Path.GetFileName(fileToZip));
 zipStream.PutNextEntry(zipEntry);
 zipStream.Write(buffer, 0, buffer.Length);
      }
      catch
      {
 res = false;
      }
      finally
      {
 if (zipEntry != null)
 {
 }

 if (zipFile != null)
 {
   zipFile.Close();
 }
 GC.Collect();
 GC.Collect(1);
      }
      return res;

    }

    /// 
    /// 递归压缩文件夹方法
    /// 
    /// 
    /// 
    /// 
    private bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName)
    {
      bool res = true;
      ZipEntry entry = null;
      FileStream fs = null;
      Crc32 crc = new Crc32();
      try
      {
 //创建当前文件夹
 entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); //加上 “/” 才会当成是文件夹创建
 s.PutNextEntry(entry);
 s.Flush();
 //先压缩文件,再递归压缩文件夹
 var filenames = Directory.GetFiles(folderToZip);
 foreach (string file in filenames)
 {
   //打开压缩文件
   fs = File.OpenRead(file);
   byte[] buffer = new byte[fs.Length];
   fs.Read(buffer, 0, buffer.Length);
   entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
   entry.DateTime = DateTime.Now;
   entry.Size = fs.Length;
   fs.Close();
   crc.Reset();
   crc.Update(buffer);
   entry.Crc = crc.Value;
   s.PutNextEntry(entry);
   s.Write(buffer, 0, buffer.Length);
 }
      }
      catch
      {
 res = false;
      }
      finally
      {
 if (fs != null)
 {
   fs.Close();
 }
 if (entry != null)
 {
 }
 GC.Collect();
 GC.Collect(1);
      }
      var folders = Directory.GetDirectories(folderToZip);
      foreach (string folder in folders)
      {
 if (!ZipFileDictory(folder, s, Path.Combine(parentFolderName, Path.GetFileName(folderToZip))))
 {
   return false;
 }
      }
      return res;
    }
  }
}

 慢慢积累,你的这些代码都是你的财富,可以帮你提高工作效率,勤勤恳恳的干好每件事情,点滴积累,开心编程。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/124277.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号