首页 > 其他分享 >.NET 压缩与解压

.NET 压缩与解压

时间:2023-10-30 23:11:34浏览次数:29  
标签:解压 fs string buffer 压缩 zos new using NET

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.IO;
  6 using ICSharpCode.SharpZipLib.Zip;
  7 using ICSharpCode.SharpZipLib.Checksums;
  8 using System.Security.Cryptography;
  9 
 10 namespace zip压缩与解压
 11 {
 12     public class ZipHelper
 13     {
 14         /// <summary>
 15         /// 压缩单个文件
 16         /// </summary>
 17         /// <param name="fileToZip">需压缩的文件名</param>
 18         /// <param name="zipFile">压缩后的文件名(文件名都是绝对路径)</param>
 19         /// <param name="level">压缩等级(0-9)</param>
 20         /// <param name="password">压缩密码(解压是需要的密码)</param>
 21         public static void ZipFile(string fileToZip, string zipFile, int level = 5, string password = "123")
 22         {
 23             if (!File.Exists(fileToZip))
 24                 throw new FileNotFoundException("压缩文件" + fileToZip + "不存在");
 25 
 26             using (FileStream fs = File.OpenRead(fileToZip))
 27             {
 28                 fs.Position = 0;//设置流的起始位置
 29                 byte[] buffer = new byte[(int)fs.Length];
 30                 fs.Read(buffer, 0, buffer.Length);//读取的时候设置Position,写入的时候不需要设置
 31                 fs.Close();
 32                 using (FileStream zfstram = File.Create(zipFile))
 33                 {
 34                     using (ZipOutputStream zipstream = new ZipOutputStream(zfstram))
 35                     {
 36                         zipstream.Password = md5(password);//设置属性的时候在PutNextEntry函数之前
 37                         zipstream.SetLevel(level);
 38                         string fileName = fileToZip.Substring(fileToZip.LastIndexOf('\\') + 1);
 39                         ZipEntry entry = new ZipEntry(fileName);
 40                         zipstream.PutNextEntry(entry);
 41                         zipstream.Write(buffer, 0, buffer.Length);
 42                     }
 43                 }
 44 
 45             }
 46         }
 47 
 48         /// <summary>
 49         /// 压缩多个文件目录
 50         /// </summary>
 51         /// <param name="dirname">需要压缩的目录</param>
 52         /// <param name="zipFile">压缩后的文件名</param>
 53         /// <param name="level">压缩等级</param>
 54         /// <param name="password">密码</param>
 55         public static void ZipDir(string dirname, string zipFile, int level = 5, string password = "123")
 56         {
 57             ZipOutputStream zos = new ZipOutputStream(File.Create(zipFile));
 58             zos.Password = md5(password);
 59             zos.SetLevel(level);
 60             addZipEntry(dirname, zos, dirname);
 61             zos.Finish();
 62             zos.Close();
 63 
 64         }
 65         /// <summary>
 66         /// 往压缩文件里面添加Entry
 67         /// </summary>
 68         /// <param name="PathStr">文件路径</param>
 69         /// <param name="zos">ZipOutputStream</param>
 70         /// <param name="BaseDirName">基础目录</param>
 71         private static void addZipEntry(string PathStr, ZipOutputStream zos, string BaseDirName)
 72         {
 73             DirectoryInfo dir = new DirectoryInfo(PathStr);
 74             foreach (FileSystemInfo item in dir.GetFileSystemInfos())
 75             {
 76                 if ((item.Attributes & FileAttributes.Directory) == FileAttributes.Directory)//如果是文件夹继续递归
 77                 {
 78                     addZipEntry(item.FullName, zos, BaseDirName);
 79                 }
 80                 else
 81                 {
 82                     FileInfo f_item = (FileInfo)item;
 83                     using (FileStream fs = f_item.OpenRead())
 84                     {
 85                         byte[] buffer = new byte[(int)fs.Length];
 86                         fs.Position = 0;
 87                         fs.Read(buffer, 0, buffer.Length);
 88                         fs.Close();
 89                         ZipEntry z_entry = new ZipEntry(item.FullName.Replace(BaseDirName, ""));
 90                         zos.PutNextEntry(z_entry);
 91                         zos.Write(buffer, 0, buffer.Length);
 92                     }
 93                 }
 94             }
 95 
 96 
 97         }
 98 
 99         /// <summary>
100         /// 解压多个文件目录
101         /// </summary>
102         /// <param name="zfile">压缩文件绝对路径</param>
103         /// <param name="dirname">解压文件目录</param>
104         /// <param name="password">密码</param>
105         public static void UnZip(string zfile, string dirname, string password)
106         {
107             if (!Directory.Exists(dirname)) Directory.CreateDirectory(dirname);
108 
109             using (ZipInputStream zis = new ZipInputStream(File.OpenRead(zfile)))
110             {
111                 zis.Password = md5(password);
112                 ZipEntry entry;
113                 while ((entry = zis.GetNextEntry()) != null)
114                 {
115                     var strArr = entry.Name.Split('\\');//这边判断压缩文件里面是否存在目录,存在的话先创建目录后继续解压
116                     if (strArr.Length > 2)        
117                         Directory.CreateDirectory(dirname + @"\" + strArr[1]);
118                     
119                     using (FileStream dir_fs = File.Create(dirname + entry.Name))
120                     {
121                         int size = 1024 * 2;
122                         byte[] buffer = new byte[size];
123                         while (true)
124                         {
125                             size = zis.Read(buffer, 0, buffer.Length);
126                             if (size > 0)
127                                 dir_fs.Write(buffer, 0, size);
128                             else
129                                 break;
130                         }
131                     }
132                 }
133             }
134         }
135 
136         private static string md5(string pwd)
137         {
138             var res = "";
139             MD5 md = MD5.Create();
140             byte[] s = md.ComputeHash(Encoding.Default.GetBytes(pwd));
141             for (int i = 0; i < s.Length; i++)
142                 res = res + s[i].ToString("X");
143 
144             return res;
145         }
146     }
147 }

 

标签:解压,fs,string,buffer,压缩,zos,new,using,NET
From: https://www.cnblogs.com/lgx5/p/17799151.html

相关文章

  • 基于Googlenet深度学习网络的矿物质种类识别matlab仿真
    1.算法运行效果图预览   2.算法运行软件版本matlab2022a 3.算法理论概述       VGG在2014年由牛津大学著名研究组vGG(VisualGeometryGroup)提出,斩获该年lmageNet竞赛中LocalizationTask(定位任务)第一名和ClassificationTask(分类任务)第二名。Clas......
  • .NET 反序列化 GetterSettingsPropertyValue 攻击链
    0x01 链路1 SettingsPropertyValueSettingsPropertyValue位于命名空间 System.Configuration,用于应用程序存储和检索设置的值,此类具有Name、IsDirty、Deserialized、PropertyValue、SerializedValue等多个公共成员,其中SerializedValue属性用于获取或者设置序列化的值,便于持久......
  • .NET集成CAS认证艰难历程
    1.前言本文不再赘述单点登录SSO原理,主要针对CAS认证服务方式集成.NET应用,从实施落地过程回顾期间遇到的坑和解决方案做些心得总结,希望对你有帮忙,如有问题,请留言一起探讨学习2.核心客户端组件DotNetCasClient.dll,本项目依赖.NET4.5版本,官方提供用于集成CAS客户端源码地......
  • 论文复现01. RestainNet
    论文名称:RestainNet:aself-superviseddigitalre-stainerforstainnormalizationarxiv: https://arxiv.org/pdf/2202.13804.pdf论文的核心内容:自监督网络,把”灰度图“重新上色成HE染色的效果训练阶段在训练阶段,将原始的RGB图像分别提取Lab空间的L通道和HE染色矩......
  • 使用 Sealos 一键部署 Kubernetes 集群
    Sealos是一款以Kubernetes为内核的云操作系统发行版,使用户能够像使用个人电脑一样简单地使用云。与此同时,Sealos还提供一套强大的工具,可以便利地管理整个Kubernetes集群的生命周期。Sealos不仅可以一键安装一个单节点的Kubernetes开发环境,还能构建数千节点的生产高可......
  • .Net Core中读取json配置文件
    1、编写实例化类。新建可供实例化的配置类JwtConfig///<summary>///Jwt的配置类///</summary>publicclassJwtConfig{///<summary>///定位///</summary>publicconststringPosition="Jwt";///<summary>///验证......
  • c#实现文件压缩的方法
    //实现一个压缩文件的方法publicstaticvoidCompressFile(stringsourceFilePath,stringzipFilePath){//如果文件没有找到,则报错if(!File.Exists(sourceFilePath)){thrownewFileNotFoundException(sourceFilePath+"文件不存在!");}//......
  • c#实现文件压缩的方法
    //实现一个压缩文件的方法publicstaticvoidCompressFile(stringsourceFilePath,stringzipFilePath){//如果文件没有找到,则报错if(!File.Exists(sourceFilePath)){thrownewFileNotFoundException(sourceFilePath+"文件不存在!");}/......
  • 解决kubernetes flannel部署的具体操作步骤
    原文:https://blog.51cto.com/u_16175446/6683522KubernetesFlannel部署教程作为一名经验丰富的开发者,我将向你介绍在Kubernetes中部署Flannel网络插件的步骤和所需的代码。Flannel是一个用于Kubernetes集群的网络解决方案,它负责为Pod提供网络互通。整体流程以下是部署Kubernete......
  • java.net.SocketException四大异常解决方案
    java.net.SocketException四大异常解决方案java.net.SocketException如何才能更好的使用呢?这个就需要我们先要了解有关这个语言的相关问题。希望大家有所帮助。那么我们就来看看有关java.net.SocketException的相关知识。第1个异常是java.net.BindException:Addressalread......