C# Zip压缩、解压
/*
*引用 NuGet包 ICSharpCode.SharpZipLib.dll
*/
public class ZipUtility
{
/// <summary>
/// 所有文件缓存
/// </summary>
List<string> files = new List<string>(); /// <summary>
/// 所有空目录缓存
/// </summary>
List<string> paths = new List<string>(); /// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="fileToZip">要压缩的文件</param>
/// <param name="zipedFile">压缩后的文件全名</param>
/// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
/// <param name="blockSize">分块大小</param>
public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
{
if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
{
throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
} FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
FileStream zipFile = File.Create(zipedFile);
ZipOutputStream zipStream = new ZipOutputStream(zipFile);
ZipEntry zipEntry = new ZipEntry(fileToZip);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
byte[] buffer = new byte[blockSize];
int size = streamToZip.Read(buffer, , buffer.Length);
zipStream.Write(buffer, , size); try
{
while (size < streamToZip.Length)
{
int sizeRead = streamToZip.Read(buffer, , buffer.Length);
zipStream.Write(buffer, , sizeRead);
size += sizeRead;
}
}
catch (Exception ex)
{
GC.Collect();
throw ex;
} zipStream.Finish();
zipStream.Close();
streamToZip.Close();
GC.Collect();
} /// <summary>
/// 压缩目录(包括子目录及所有文件)
/// </summary>
/// <param name="rootPath">要压缩的根目录</param>
/// <param name="destinationPath">保存路径</param>
/// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)
{
GetAllDirectories(rootPath); /* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾
{ rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\" }
*/
//string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
Crc32 crc = new Crc32();
ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));
outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression
foreach (string file in files)
{
FileStream fileStream = File.OpenRead(file);//打开压缩文件
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, , buffer.Length);
ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
entry.DateTime = DateTime.Now; entry.Size = fileStream.Length;
fileStream.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
outPutStream.PutNextEntry(entry);
outPutStream.Write(buffer, , buffer.Length);
} this.files.Clear(); foreach (string emptyPath in paths)
{
ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");
outPutStream.PutNextEntry(entry);
} this.paths.Clear();
outPutStream.Finish();
outPutStream.Close();
GC.Collect();
} /// <summary>
/// 取得目录下所有文件及文件夹,分别存入files及paths
/// </summary>
/// <param name="rootPath">根目录</param>
private void GetAllDirectories(string rootPath)
{
string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录
foreach (string path in subPaths)
{
GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
}
string[] files = Directory.GetFiles(rootPath);
foreach (string file in files)
{
this.files.Add(file);//将当前目录中的所有文件全名存入文件List
}
if (subPaths.Length == files.Length && files.Length == )//如果是空目录
{
this.paths.Add(rootPath);//记录空目录
}
} /// <summary>
/// 解压缩文件(压缩文件中含有子目录)
/// </summary>
/// <param name="zipfilepath">待解压缩的文件路径</param>
/// <param name="unzippath">解压缩到指定目录</param>
/// <returns>解压后的文件列表</returns>
public List<string> UnZip(string zipfilepath, string unzippath)
{
//解压出来的文件列表
List<string> unzipFiles = new List<string>(); //检查输出目录是否以“\\”结尾
if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
{
unzippath += "\\";
} ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(unzippath);
string fileName = Path.GetFileName(theEntry.Name); //生成解压目录【用户解压到硬盘根目录时,不需要创建】
if (!string.IsNullOrEmpty(directoryName))
{
Directory.CreateDirectory(directoryName);
} if (fileName != String.Empty)
{
//如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
if (theEntry.CompressedSize == )
continue;
//解压文件到指定的目录
directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
//建立下面的目录和子目录
Directory.CreateDirectory(directoryName); //记录导出的文件
unzipFiles.Add(unzippath + theEntry.Name); FileStream streamWriter = File.Create(unzippath + theEntry.Name); int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
GC.Collect();
return unzipFiles;
} public string GetZipFileExtention(string fileFullName)
{
int index = fileFullName.LastIndexOf(".");
if (index <= )
{
throw new Exception("源包文件不是压缩文件");
} //extension string
string ext = fileFullName.Substring(index); if (ext == ".rar" || ext == ".zip")
{
return ext;
}
else
{
//The source package file is not a compress file
throw new Exception("源包文件不是压缩文件");
}
}
}
C# Zip压缩、解压的更多相关文章
- linux查看文件夹大小,备份文件夹zip压缩解压
linux查看文件夹大小,备份文件夹zip压缩解压 du -sh : 查看当前目录总共占的容量.而不单独列出各子项占用的容量 du -lh --max-depth=1 : 查看当前目录下一级子文件和子 ...
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志
C#实现多级子目录Zip压缩解压实例 参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩, ...
- C# ZIP 压缩解压
ZIP流是在NetFramework4.5 引入的目的是为了能够更好的操作ZIP文件,进行压缩解压等操作.与ZIP流相关的几个类是: ZipArchive 代表一个ZIP的压缩包文件 ZipArchi ...
- C#实现Zip压缩解压实例【转】
本文只列举一个压缩帮助类,使用的是有要添加一个dll引用ICSharpCode.SharpZipLib.dll[下载地址]. 另外说明一下的是,这个类压缩格式是ZIP的,所以文件的后缀写成 .zip. ...
- C#实现多级子目录Zip压缩解压实例
参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩,类似winrar,可以选择 ...
- C#实现Zip压缩解压实例
原文地址:https://www.cnblogs.com/GoCircle/p/6544678.html 本文只列举一个压缩帮助类,使用的是有要添加一个dll引用ICSharpCode.SharpZi ...
- zip压缩解压
zip在linux中使用相对不太频繁,但是在window中使用频繁! zip参数 -q //不显示指令的执行过程,静默执行-r //递归处理文件-T //检测zip文件是否可用-u //更新文件,根据 ...
- (转载)C#压缩解压zip 文件
转载之: C#压缩解压zip 文件 - 大气象 - 博客园http://www.cnblogs.com/greatverve/archive/2011/12/27/csharp-zip.html C# ...
- linux命令:压缩解压命令
压缩解压命令:gzip 命令名称:gzip 命令英文原意:GNU zip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip 选项 [文件] 功能描述:压缩文件 压缩后文件格式:g ...
- linux 压缩 解压zip 命令
将当前目录下的所有文件和文件夹全部压缩成test.zip文件,-r表示递归压缩子目录下所有文件zip -r test.zip ./* 打包目录zip test2.zip test2/*解压test.z ...
随机推荐
- Linux ps 查看进程
[root@wang /]# ps aux ps -elf ^C [root@wang /]# ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIM ...
- 【Cisco】实现同一个路由器一个端口用动态路由,另一个端口用静态路由
一.先构建以下网络图: 准备三台路由器,三台交换机,三台主机,连接所有设备并配置端口IP和网关,DCE端口的时钟频率都设置为64000.
- poj2486 Apple Tree (树形dp+分组背包)
题目链接:https://vjudge.net/problem/POJ-2486 题意:一棵点权树,起点在1,求最多经过m条边的最大点权和. 思路: 树形dp经典题.用3维状态,dp[u][j][0/ ...
- jumpserver0.4.0与python3版本安装
环境: 系统:CentOS 6.5 Python版本:Python3.6 安装目录:/Data/apps/ 一. 环境准备: 1. 基本工具库: # yum -y install sqlite-de ...
- storm并行度核心概念介绍剖析
一.Storm的并行介绍 并行意味着多个任务在不同的节点上,且每个节点都可独立运行,并且相互之间没有依赖. 而在storm上,storm提交的jobs(任务)通过nimbus分发到多个supervis ...
- 解决Eclipse中文文档注释错位-处女座的悲哀!
1.右键打开eclips属性 2.选择兼容性为win8,然后打开Eclipse即可解决 作者:醉烟 出处:https://www.cnblogs.com/WangLei2018/ 本文版权归作者 ...
- QT 打包exe
QT打包主要方法: 1.把无措的代码进行Release编译 2.在运行完后,找到运行后生成的目录,以下是我的文件,名为result,运行类型有两种,一种是Debug,另一种是Release,我们需要的 ...
- opencv实现人脸识别(五) 运用tkinter进行GUI绘制 整合人脸识别模块
因为之前学习过tkinter库,所以在学习了人脸识别模块的编写后, 打算绘制一个简单的GUI来应用人脸识别功能. 主界面如下所示: 签到打开在点开后直接进行人脸识别,如果成功则自动关闭视频窗口. 录入 ...
- gulp做简单的js压缩
安装工具 全局安装npm install --global gulp 项目的依赖安装npm install --save-dev gulp npm install --save-dev gulp-re ...
- WPF入门(3)——命令
命令是ICommand类型的属性,binding到控件上,用于代替事件,个人认为事件也很好,命令只是轻度解耦前后端. 闲话少说,上代码,示例是ScreenToGif的源代码中的一个命令: public ...