首页 > 编程语言 >C#使用ICSharpCode.SharpZipLib.dll进行文件的压缩与解压功能

C#使用ICSharpCode.SharpZipLib.dll进行文件的压缩与解压功能

时间:2024-04-07 10:57:23浏览次数:25  
标签:fs string C# dll buffer File new ICSharpCode using

原文链接:https://www.jb51.net/article/131706.htm

网上大部分都挺复杂

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.Security.Cryptography;
namespace zip压缩与解压
{
 public class ZipHelper
 {
  /// <summary>
  /// 压缩单个文件
  /// </summary>
  /// <param name="fileToZip">需压缩的文件名</param>
  /// <param name="zipFile">压缩后的文件名(文件名都是绝对路径)</param>
  /// <param name="level">压缩等级(0-9)</param>
  /// <param name="password">压缩密码(解压是需要的密码)</param>
  public static void ZipFile(string fileToZip, string zipFile, int level = 5, string password = "123")
  {
   if (!File.Exists(fileToZip))
    throw new FileNotFoundException("压缩文件" + fileToZip + "不存在");
   using (FileStream fs = File.OpenRead(fileToZip))
   {
    fs.Position = 0;//设置流的起始位置
    byte[] buffer = new byte[(int)fs.Length];
    fs.Read(buffer, 0, buffer.Length);//读取的时候设置Position,写入的时候不需要设置
    fs.Close();
    using (FileStream zfstram = File.Create(zipFile))
    {
     using (ZipOutputStream zipstream = new ZipOutputStream(zfstram))
     {
      zipstream.Password = md5(password);//设置属性的时候在PutNextEntry函数之前
      zipstream.SetLevel(level);
      string fileName = fileToZip.Substring(fileToZip.LastIndexOf('\\') + 1);
      ZipEntry entry = new ZipEntry(fileName);
      zipstream.PutNextEntry(entry);
      zipstream.Write(buffer, 0, buffer.Length);
     }
    }
   }
  }
  /// <summary>
  /// 压缩多个文件目录
  /// </summary>
  /// <param name="dirname">需要压缩的目录</param>
  /// <param name="zipFile">压缩后的文件名</param>
  /// <param name="level">压缩等级</param>
  /// <param name="password">密码</param>
  public static void ZipDir(string dirname, string zipFile, int level = 5, string password = "123")
  {
   ZipOutputStream zos = new ZipOutputStream(File.Create(zipFile));
   zos.Password = md5(password);
   zos.SetLevel(level);
   addZipEntry(dirname, zos, dirname);
   zos.Finish();
   zos.Close();
  }
  /// <summary>
  /// 往压缩文件里面添加Entry
  /// </summary>
  /// <param name="PathStr">文件路径</param>
  /// <param name="zos">ZipOutputStream</param>
  /// <param name="BaseDirName">基础目录</param>
  private static void addZipEntry(string PathStr, ZipOutputStream zos, string BaseDirName)
  {
   DirectoryInfo dir = new DirectoryInfo(PathStr);
   foreach (FileSystemInfo item in dir.GetFileSystemInfos())
   {
    if ((item.Attributes & FileAttributes.Directory) == FileAttributes.Directory)//如果是文件夹继续递归
    {
     addZipEntry(item.FullName, zos, BaseDirName);
    }
    else
    {
     FileInfo f_item = (FileInfo)item;
     using (FileStream fs = f_item.OpenRead())
     {
      byte[] buffer = new byte[(int)fs.Length];
      fs.Position = 0;
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
      ZipEntry z_entry = new ZipEntry(item.FullName.Replace(BaseDirName, ""));
      zos.PutNextEntry(z_entry);
      zos.Write(buffer, 0, buffer.Length);
     }
    }
   }
  }
  /// <summary>
  /// 解压多个文件目录
  /// </summary>
  /// <param name="zfile">压缩文件绝对路径</param>
  /// <param name="dirname">解压文件目录</param>
  /// <param name="password">密码</param>
  public static void UnZip(string zfile, string dirname, string password)
  {
   if (!Directory.Exists(dirname)) Directory.CreateDirectory(dirname);
   using (ZipInputStream zis = new ZipInputStream(File.OpenRead(zfile)))
   {
    zis.Password = md5(password);
    ZipEntry entry;
    while ((entry = zis.GetNextEntry()) != null)
    {
     var strArr = entry.Name.Split('\\');//这边判断压缩文件里面是否存在目录,存在的话先创建目录后继续解压
     if (strArr.Length > 2)  
      Directory.CreateDirectory(dirname + @"\" + strArr[1]);
     using (FileStream dir_fs = File.Create(dirname + entry.Name))
     {
      int size = 1024 * 2;
      byte[] buffer = new byte[size];
      while (true)
      {
       size = zis.Read(buffer, 0, buffer.Length);
       if (size > 0)
        dir_fs.Write(buffer, 0, size);
       else
        break;
      }
     }
    }
   }
  }
  private static string md5(string pwd)
  {
   var res = "";
   MD5 md = MD5.Create();
   byte[] s = md.ComputeHash(Encoding.Default.GetBytes(pwd));
   for (int i = 0; i < s.Length; i++)
    res = res + s[i].ToString("X");
   return res;
  }
 }
}

  调用函数如下:

static void Main(string[] args)
  {
   var str = @"\学籍导入模板.xls";
   //var arr=str.Split('\\');
   var filePath = @"D:\程序文件\VS2010学习\StudyProgram\zip压缩与解压\File\学籍导入模板.xls";
   //ZipHelper.ZipFile(filePath, @"D:\程序文件\VS2010学习\StudyProgram\zip压缩与解压\File\test.zip", 6, "123");
   var dirPath = @"D:\程序文件\VS2010学习\StudyProgram\zip压缩与解压";
   //ZipHelper.ZipDir(dirPath + @"\File", dirPath + @"\File.zip", 6, "huage");
   ZipHelper.UnZip(dirPath + @"\File.zip", dirPath + @"\test", "huage");
   Console.ReadKey();
  }

  

标签:fs,string,C#,dll,buffer,File,new,ICSharpCode,using
From: https://www.cnblogs.com/Dongmy/p/18118594

相关文章

  • 19.14.Android四大组件之一活动单元Activity 下
    任务栈和启动模式Fragment1.关于任务栈和启动模式(了解)Android中的任务栈压栈和出栈即开启的往里面压位于最上面找哪个上面的被弹出启动模式四种模式:standard每启动一个Activity就创建一个实例singleTop模式判断是否存在Activity位于栈顶如果存在直接复......
  • centos7:编译升级 openssh:主要参考“https://github.com/boypt/openssh-rpms”
    参考“https://github.com/boypt/openssh-rpms”  “Releases·boypt/openssh-rpms(github.com)” 安装人家大牛的文档来操作即可。可选的,自行定制 version.env,可进行各种组合! BackportOpenSSHRPM/SRPMforoldCentOSAsimplescripttobuildlatestOpen......
  • 03-template-advance
    03-TemplateAdvance源作者地址:https://github.com/bonfy/go-mega仅个人学习使用学习完第二章之后,你对模板已经有了基本的认识本章将讨论Go的组合特性,以及建立一个通用的调用模板的方法本章的GitHub链接为:Source,Diff,Zip匿名组合匿名组合其实是Go里的一个非常......
  • 02-template-basic
    02-TemplateBasic源作者地址:https://github.com/bonfy/go-mega仅个人学习使用学习完第一章之后,我们已经拥有了虽然一个简单,但可以成功运行Web应用本章将沿用这个应用,在此之上,加入模版渲染,使得页面更丰富本章的GitHub链接为:Source,Diff,Zip什么是模板微博应用程序的......
  • copier:万能的对象拷贝偷懒神器
    copier:万能的对象拷贝偷懒神器原创 golang学习记 golang学习记 2024-04-0710:29 四川 听全文如果你干什么事都专注一点那么你就会超过80%的人如果你在一个点上坚持5年那么你进入10%都有可能 我见过的最美的一天是你穿过人群找到我的那一天 g......
  • docker清理空间
    查看磁盘占用情况df-lh查看当前目录占用情况du-sh*查看docker占用情况dockersystemdfTYPE 列出了docker使用磁盘的4种类型:Images:所有镜像占用的空间,包括拉取下来的镜像,和本地构建的。Containers:运行的容器占用的空间,表示每个容器的读写层的空间。LocalV......
  • LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows
    原题链接在这里:https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/description/题目:Youaregivenan mxn matrix mat thathasitsrowssortedinnon-decreasingorderandaninteger k.Youareallowedtochoose exactlyo......
  • C# 文件、文件夹常规创建删除操作实例
    原文链接:https://blog.csdn.net/weixin_45023644/article/details/121951840C#的文件操作的功能是非常丰富的。他们大多来自System.IO类,比如:File、Directory、BinaryReader、BinaryWriter、DirectoryInfo、FileStream、MemoryStream、Path、StringWriter等等。当然,其它很多类中也......
  • 基于EP4CE6F17C8的FPGA矩阵键盘实例
    一、电路模块1、数码管开发板板载了6个数码管,全部为共阳型,原理图如下图所示,段码端引脚为DIG[0]~DIG[7]共8位(包含小数点),位选端引脚为SEL[0]~SEL[5]共6位。端口均为低电平有效。其实物图如下所示。数码管引脚分配见下表。2、时钟晶振开发板板载了一个50MHz的有源晶振,为系统......
  • QCustomPlot使用
    QCustomPlot用法及源代码放大缩小、动态增加数据、鼠标拖拽矩形框选曲线数据(T1~T2时间段内的数据)鼠标点击显示数据点x缩放、y缩放、还原、截图等功能通用创建文件夹功能;通用MessageBox,对QMessageBox进行重写源码如下CustomPlotEx.h#pragmaonce#include<QW......