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 ...
随机推荐
- Hadoop学习笔记之二 文件操作
HDFS分布式文件系统:优点:支持超大文件存储.流式访问.一次写入多次读取.缺点:不适应大量小文件.不适应低时延的数据访问.不适应多用户访问任意修改文件. 1.hadoop用于大数据处理,在数据量较小 ...
- Aspose.Words提取word文档中的图片文件
/// <summary> /// 提取word中的图片 /// </summary> /// <param name="filePath">w ...
- hdoj3586 (树形dp)
题目链接:https://vjudge.net/problem/HDU-3586 题意:一棵边权树,要删掉一些边使得每个叶子结点不能到达树根,且这些边的权值<=上限Max,且边权和小于m,求最小 ...
- 飞腾1500A 上面银河麒麟操作系统 进行远程以及添加用户的方法 linux xrdp
1. 安装远程用的软件: sudo apt-get install xrdp vnc4server xbase-clients systemctl enable xrdp systemctl star ...
- AndroidStudio布局编辑器强制刷新布局界面
用AndroidStudio布局编辑器编辑界面的时候,在selector里调整按钮的颜色,调整后的颜色经常无法实时显示在布局编辑器里,每次都重新运行程序查看界面又非常麻烦和低效,可以用以下方法解决: ...
- System x 服务器制作ServerGuide U盘安装Windows Server 2008 操作系统 --不格式化盘
1.全格式化 用ServerGuide10.5 刻录成U盘 下载附件中的Rufus 3.6工具,并制作引导U盘 以管理员权限打开Rufus 3.6, 选择镜像文件 2.不格式化,仅安装C盘下载老毛桃U ...
- Kafka 原理
消息队列内部实现原理 两种消息传输方式 Kafka kafka 简介 kafka 集群角色 Kafka 工作流程分析 Kafka 生产过程分析 写入方式 分区(partition) 副本(replic ...
- java日志框架系列(1):slf4j框架简介及依赖
1.slf4j日志框架 1.简介 slf4j只是是日志规范,即只定义了接口,并没有实现这些接口. SLF4J的全称是Simple Logging Facade for Java,即简单日志门面.SLF ...
- cmake 简单build和删除
mkdir build cd build cmake .. make
- 织梦DedeCMS给栏目添加缩略图调用的方法
织梦DedeCMS的栏目调用仅仅只有文字调用,没有栏目缩略图调用,而我们有时候又需要给栏目添加缩略图,并能够在前台调用,就可以试试通过下面的方法,给栏目添加缩略图. 首先要给栏目数据库表添加一个存储缩 ...