今天梳理一下项目中用到的压缩、解压文件夹或文件的方法,发现因为需求不同,已经用了好几个不同组件。今天就好好整理记录下,别下次遇到需求又重头开始了。

DotNetZip

DotNetZip是一个开源的免费类库,主要提供了快速操作zip文件的工具集,VB、C#任何.Net语言都可以通过它创建、解压缩zip文件。我使用该类库最主要的目的还是因为它可以创建带密码保护的压缩文件。

只有设置了zip.Password = "password"之后,被压缩的文件才会有密码保护

/// <summary>
/// 压缩文件/文件夹
/// </summary>
/// <param name="filePath">需要压缩的文件/文件夹路径</param>
/// <param name="zipPath">压缩文件路径(zip后缀)</param>
/// <param name="password">密码</param>
/// <param name="filterExtenList">需要过滤的文件后缀名</param>
public static void CompressionFile(string filePath, string zipPath, string password = "", List<string> filterExtenList = null)
{
try
{
using (ZipFile zip = new ZipFile(Encoding.UTF8))
{
if (!string.IsNullOrWhiteSpace(password))
{
zip.Password = password;
}
if (Directory.Exists(filePath))
{
if (filterExtenList == null)
zip.AddDirectory(filePath);
else
AddDirectory(zip, filePath, filePath, filterExtenList);
}
else if (File.Exists(filePath))
{
zip.AddFile(filePath,"");
}
zip.Save(zipPath);
}
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 添加文件夹
/// </summary>
/// <param name="zip">ZipFile对象</param>
/// <param name="dirPath">需要压缩的文件夹路径</param>
/// <param name="rootPath">根目录路径</param>
/// <param name="filterExtenList">需要过滤的文件后缀名</param>
public static void AddDirectory(ZipFile zip, string dirPath, string rootPath, List<string> filterExtenList)
{
var files = Directory.GetFiles(dirPath);
for (int i = 0; i < files.Length; i++)
{
//如果Contains不支持第二个参数,就用.ToLower()
if (filterExtenList == null || (filterExtenList != null && !filterExtenList.Any(d => Path.GetExtension(files[i]).Contains(d, StringComparison.OrdinalIgnoreCase))))
{
//获取相对路径作为zip文件中目录路径
zip.AddFile(files[i], Path.GetRelativePath(rootPath, dirPath)); //如果没有Path.GetRelativePath方法,可以用下面代码替换
//string relativePath = Path.GetFullPath(dirPath).Replace(Path.GetFullPath(rootPath), "");
//zip.AddFile(files[i], relativePath);
}
}
var dirs = Directory.GetDirectories(dirPath);
for (int i = 0; i < dirs.Length; i++)
{
AddDirectory(zip, dirs[i], rootPath, filterExtenList);
}
}

SharpCompress

SharpCompress是用到现在,感觉功能最强大的压缩、解压开源插件。它支持处理zip、rar、7z等多种格式的压缩文件,使用方式也很简单。当然,最让我难受的是创建压缩文件的时候没法设置密码~所以才有了上面DotnetZip的代码。

SharpCompress版本不同,设置ArchiveEncoding的方式也不同,默认设置了UTF8防止解压乱码。

通过设置ArchiveType切换生成不同格式压缩文件

/// <summary>
/// 压缩文件/文件夹
/// </summary>
/// <param name="filePath">需要压缩的文件/文件夹路径</param>
/// <param name="zipPath">压缩文件路径(zip后缀)</param>
/// <param name="filterExtenList">需要过滤的文件后缀名</param>
public static void CompressionFile(string filePath, string zipPath, List<string> filterExtenList = null)
{
try
{
using (var zip = File.Create(zipPath))
{
var option = new WriterOptions(CompressionType.Deflate)
{
ArchiveEncoding = new SharpCompress.Common.ArchiveEncoding()
{
Default = Encoding.UTF8
}
};
using (var zipWriter = WriterFactory.Open(zip, ArchiveType.Zip, option))
{
if (Directory.Exists(filePath))
{
//添加文件夹
zipWriter.WriteAll(filePath, "*",
(path) => filterExtenList == null ? true : !filterExtenList.Any(d => Path.GetExtension(path).Contains(d, StringComparison.OrdinalIgnoreCase)), SearchOption.AllDirectories);
}
else if (File.Exists(filePath))
{
zipWriter.Write(Path.GetFileName(filePath), filePath);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 解压文件
/// </summary>
/// <param name="zipPath">压缩文件路径</param>
/// <param name="dirPath">解压到文件夹路径</param>
/// <param name="password">密码</param>
public static void DeCompressionFile(string zipPath, string dirPath, string password = "")
{
if (!File.Exists(zipPath))
{
throw new ArgumentNullException("zipPath压缩文件不存在");
}
Directory.CreateDirectory(dirPath);
try
{
using (Stream stream = File.OpenRead(zipPath))
{
var option = new ReaderOptions()
{
ArchiveEncoding = new SharpCompress.Common.ArchiveEncoding()
{
Default = Encoding.UTF8
}
};
if (!string.IsNullOrWhiteSpace(password))
{
option.Password = password;
} var reader = ReaderFactory.Open(stream, option);
while (reader.MoveToNextEntry())
{
if (reader.Entry.IsDirectory)
{
Directory.CreateDirectory(Path.Combine(dirPath, reader.Entry.Key));
}
else
{
//创建父级目录,防止Entry文件,解压时由于目录不存在报异常
var file = Path.Combine(dirPath, reader.Entry.Key);
Directory.CreateDirectory(Path.GetDirectoryName(file));
reader.WriteEntryToFile(file);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}

总结

相似的插件还有SharpZipLib(支持更多的压缩格式)、SevenZipSharp(专注处理7z格式压缩文件)等,它们也都有各自的优缺点。但总的来说,上面的两个组件已经满足日常工作中的大部分需求,遇到相同问题的朋友可以参考下~

C# 压缩、解压文件夹或文件(带密码)的更多相关文章

  1. Linux压缩解压 tar.gz格式的文件.查看tomcat是否运行

    tar命令详解 -c: 建立压缩档案 -x:解压 -t:查看内容 -r:向压缩归档文件末尾追加文件 -u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用 ...

  2. 【转载】.NET压缩/解压文件/夹组件

    转自:http://www.cnblogs.com/asxinyu/archive/2013/03/05/2943696.html 阅读目录 1.前言 2.关于压缩格式和算法的基础 3.几种常见的.N ...

  3. linux查看文件夹大小,备份文件夹zip压缩解压

    linux查看文件夹大小,备份文件夹zip压缩解压 du -sh : 查看当前目录总共占的容量.而不单独列出各子项占用的容量 du -lh --max-depth=1 : 查看当前目录下一级子文件和子 ...

  4. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  5. huffman压缩解压文件【代码】

    距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...

  6. 【.Net Core】ZipFile类--文件的压缩解压

    NuGet引用官网自带的System.IO.Compression.ZipFile; var filename = "测试压缩解压文件"; var path = Directory ...

  7. (转载)C#压缩解压zip 文件

    转载之: C#压缩解压zip 文件 - 大气象 - 博客园http://www.cnblogs.com/greatverve/archive/2011/12/27/csharp-zip.html C# ...

  8. tar 解压某个指定的文件或者文件夹

    1. 先查看压缩文档中有那些文件,如果都不清楚文件内容,然后就直接解压,这个是不可能的 使用#tar -tf 压缩包名称,可以查看压缩包内容 2.解压某个文件 tar -zxvf zabbix.tar ...

  9. JAVA压缩解压ZIP文件,中文乱码还需要ANT.JAR包

    package zip; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStrea ...

随机推荐

  1. 物联网实验Arduino(1)

    回顾 我们使用的平台: Arduino 入门实验1 眨眼睛 /* Blink Turns an LED on for one second, then off for one second, repe ...

  2. Spring Security学习笔记一

    一.使用Spring Security 1.在pom 文件中添加Spring Security的依赖. <dependency> <groupId>org.springfram ...

  3. 铁大树洞与市面上现有APP对比

    写在前面 铁大树洞这款APP严格来说并没有可以参照的对象,但如果非要说的话也可以有.这里我们选取百度贴吧进行对比. 百度贴吧 可以看到,百度贴吧的贴吧首页排版要更加好看,且在首页添加了各种分类.也许我 ...

  4. 小谢第50问:vuex的五个属性-使用-介绍

    一.Vuex 是什么? 官网:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 关键词:状态 ...

  5. 1、Java 开发环境配置

    Java 开发环境配置 在本章节中我们将为大家介绍如何搭建Java开发环境. Windows 上安装开发环境 Linux 上安装开发环境 安装 Eclipse 运行 Java window系统安装ja ...

  6. 网络协议: TCP/IP 和UDP/IP

    网络协议: TCP/IP 和UDP/IP TCP/IP TCP/IP(Transmission Control Protocol/Internet Protocol)是一种可靠的网络数据传输控制协议. ...

  7. 【Python笔记】2020年7月30日练习【汉诺塔游戏】

    学习教程:廖雪峰-Python教程-函数-递归函数 学习笔记: 实例代码如下: def move(n, a, b, c): if n == 1: print(a,'--->', c) else: ...

  8. 咕咕咕清单(SCOI2020前)

    本篇博客已停更 本篇博客已停更 本篇博客已停更 吐槽区: 2020.04.15: 从今天起我做过的题目都记录一下,想不想写题解就另说了 2020.04.17: 写了两天之后真实的发现这是博主的摸鱼日记 ...

  9. troubleshoot之:用control+break解决线程死锁问题

    目录 简介 死锁的代码 control+break命令 Full thread dump 死锁检测 Heap信息 总结 简介 如果我们在程序中遇到线程死锁的时候,该怎么去解决呢? 本文将会从一个实际的 ...

  10. k8s使用需认证的私服仓库

    本文内容 在K8s中使用需认证的私服仓库需要导入认证信息到集群中,常规导入方式有两种: 使用Docker已登录的仓库密文导入 使用命令行创建Secret对象导入 本文介绍的就是以上两种方法. 使用Do ...