使用SharpZipLib实现文件压缩、解压
接口
public interface IUnZip
{
/// <summary>
/// 功能:解压zip格式的文件。
/// </summary>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
/// <param name="password">压缩包密码</param>
/// <returns>解压后文件所在的文件夹</returns>
string UnZipFile(string zipFilePath, string unZipDir = null, string password = null);
}
public interface IZip
{
/// <summary>
/// 将选定的文件压入一个目标zip中
/// </summary>
/// <param name="list">选定的文件/文件夹(路径的集合)</param>
/// <param name="targetFileName">压缩后得到的zip保存路径</param>
/// <param name="password">压缩包密码</param>
/// <param name="overwrite">如果Zip文件已存在,是否覆盖</param>
/// <param name="level">压缩等级0—9</param>
/// <returns>压缩包路径</returns>
void Compress(List<string> list, string targetFileName, string password = null, bool overwrite = true, int level = 9);
/// <summary>
/// 将选定的文件压入一个目标zip中
/// </summary>
/// <param name="fileOrDir">选定的文件/文件夹</param>
/// <param name="targetFileName">压缩后得到的zip保存路径</param>
/// <param name="password">压缩包密码</param>
/// <param name="overwrite">如果Zip文件已存在,是否覆盖</param>
/// <param name="level">压缩等级0—9</param>
/// <returns>压缩包路径</returns>
void Compress(string fileOrDir, string targetFileName, string password = null, bool overwrite = true, int level = 9);
}
public interface IZipHelper:IZip,IUnZip
{
}
实现
public class ZipHelper : IZipHelper
{
#region 压缩文件
/// <inheritdoc/>
public void Compress(string fileOrDir, string targetFileName, string password = null, bool overwrite = true, int level = 9)
{
List<string> list = new List<string> { fileOrDir };
Compress(list, targetFileName, password, overwrite,level);
}
/// <inheritdoc/>
public void Compress(List<string> list, string targetFileName, string password = null, bool overwrite = true,int level = 9)
{
CheckForCompress(list, targetFileName, overwrite);
//如果已经存在目标文件,删除
if (File.Exists(targetFileName))
{
File.Delete(targetFileName);
}
ZipOutputStream zips = null;
FileStream fileStream = null;
try
{
fileStream = File.Create(targetFileName);
zips = new ZipOutputStream(fileStream);
zips.SetLevel(level % 10); //压缩等级
zips.Password = password;
foreach (string dir in list)
{
if (File.Exists(dir))
{
AddFile("",dir, zips);
}
else
{
CompressFolder("", dir, zips);
}
}
zips.Finish();
}
catch { throw; }
finally
{
if(fileStream!= null)
{
fileStream.Close();
fileStream.Dispose();
}
if(zips!= null)
{
zips.Close();
zips.Dispose();
}
}
}
#region private
private void CheckForCompress(List<string> files, string targetFileName, bool overwrite)
{
//因为files可能来自不同的文件夹,所以不方便自动提供一个默认文件夹,需要提供
if (!overwrite && File.Exists(targetFileName))
{
throw new Exception("目标zip文件已存在!");
}
//待压入的文件或文件夹需要真实存在
foreach (var item in files)
{
if (!File.Exists(item) && !Directory.Exists(item))
{
throw new Exception($"文件/文件夹【{item}】不存在!");
}
}
//不能有同名的文件/文件夹
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var item in files)
{
string item_ = item.TrimEnd('/', '\\');
string fileName = Path.GetFileName(item_);
if (dic.ContainsKey(fileName))
{
throw new Exception($"选中的文件/文件夹中存在同名冲突:【{dic[fileName]}】,【{item_}】");
}
else
{
dic[fileName] = item_;
}
}
}
private void AddFile(string orignalDir, string file, ZipOutputStream zips)
{
//文件
FileStream StreamToZip = null;
try
{
//加入ZIP文件条目(为压缩文件流提供一个容器)
StreamToZip = new FileStream(file, FileMode.Open, FileAccess.Read);
string fileName = Path.GetFileName(file);
if (!string.IsNullOrEmpty(orignalDir))
{
fileName = orignalDir + Path.DirectorySeparatorChar + fileName;
}
ZipEntry z = new ZipEntry(fileName);
zips.PutNextEntry(z);
//写入文件流
int pack = 10240; //10Kb
byte[] buffer = new byte[pack];
int size = StreamToZip.Read(buffer, 0, buffer.Length);
while (size > 0)
{
zips.Write(buffer, 0, size);
size = StreamToZip.Read(buffer, 0, buffer.Length);
}
}
catch { throw; }
finally
{
if (StreamToZip != null)
{
StreamToZip.Close();
StreamToZip.Dispose();
}
}
}
private void AddFolder(string orignalDir, string folder, ZipOutputStream zips)
{
//文件夹
folder = folder.TrimEnd('/','\\');
string fileName = Path.GetFileName(folder);
if (!string.IsNullOrEmpty(orignalDir))
{
fileName = orignalDir + Path.DirectorySeparatorChar + fileName ;
}
fileName += Path.DirectorySeparatorChar;
ZipEntry z = new ZipEntry(fileName);
zips.PutNextEntry(z);
}
/// <summary>
/// 递归压缩文件夹内所有文件和子文件夹
/// </summary>
/// <param name="orignalDir">外层文件夹</param>
/// <param name="dir">被压缩文件夹</param>
/// <param name="zips">流</param>
private void CompressFolder(string orignalDir,string dir, ZipOutputStream zips)
{
// 压缩当前文件夹下所有文件
string[] names = Directory.GetFiles(dir);
foreach (string fileName in names)
{
AddFile(orignalDir,fileName, zips);
}
// 压缩子文件夹
names = Directory.GetDirectories(dir);
foreach (string folderName in names)
{
AddFolder(orignalDir, folderName, zips);
string _orignalDir = Path.GetFileName(folderName);
if (!string.IsNullOrEmpty(orignalDir))
{
_orignalDir = orignalDir + Path.DirectorySeparatorChar + _orignalDir;
}
CompressFolder(_orignalDir, folderName, zips);
}
}
#endregion private
#endregion 压缩文件
#region 解压文件
/// <inheritdoc/>
public string UnZipFile(string zipFilePath, string unZipDir = null,string password = null)
{
if (!File.Exists(zipFilePath))
{
throw new Exception($"压缩文件【{zipFilePath}】不存在!");
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (string.IsNullOrWhiteSpace(unZipDir))
{
unZipDir = Path.GetDirectoryName(zipFilePath);
string name = Path.GetFileNameWithoutExtension(zipFilePath);
unZipDir = Path.Combine(unZipDir, name);
}
string unZipDir2 = unZipDir;
char lastChar = unZipDir[unZipDir.Length - 1];
if (lastChar != '/' && lastChar != '\\')
{
unZipDir += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
//解压
UnZipProcess(zipFilePath, unZipDir, password);
return unZipDir2;
}
private void UnZipProcess(string zipFilePath, string unZipDir, string password)
{
ZipInputStream zipInput = null;
FileStream fileStream = null;
try
{
fileStream = File.OpenRead(zipFilePath);
zipInput = new ZipInputStream(fileStream);
zipInput.Password = password;
ZipEntry theEntry;
while ((theEntry = zipInput.GetNextEntry()) != null)
{
string tempPath = unZipDir + theEntry.Name;
if (theEntry.IsDirectory)
{
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
}
else
{
using (FileStream streamWriter = File.Create(tempPath))
{
byte[] buffer = new byte[10240];
int size = zipInput.Read(buffer, 0, buffer.Length);
while (size > 0)
{
streamWriter.Write(buffer, 0, size);
size = zipInput.Read(buffer, 0, buffer.Length);
}
}
}
}
}
catch
{
throw;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
fileStream.Dispose();
}
if (zipInput != null)
{
zipInput.Close();
zipInput.Dispose();
}
}
}
#endregion
}
使用SharpZipLib实现文件压缩、解压的更多相关文章
- 使用SharpZIpLib写的压缩解压操作类
使用SharpZIpLib写的压缩解压操作类,已测试. public class ZipHelper { /// <summary> /// 压缩文件 /// </summary&g ...
- Linux 之 文件压缩解压
文件压缩解压 参考教程:[千峰教育] 命令: gzip: 作用:压缩文件,只能是单个文件,不能是多个,也不能是目录. 格式:gzip file 说明:执行命令会生成file.gz,删除原来的file ...
- linux驱动系列之文件压缩解压小节(转)
转至网页:http://www.jb51.net/LINUXjishu/43356.html Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通 ...
- 分享一个ASP.NET 文件压缩解压类 C#
需要引用一个ICSharpCode.SharpZipLib.dll using System; using System.Collections.Generic; using System.Linq; ...
- C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用
工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个 ...
- iOS - File Archive/UnArchive 文件压缩/解压
1.ZipArchive 方式 ZipArchive 只能对 zip 类文件进行压缩和解压缩 GitHub 网址:https://github.com/ZipArchive/ZipArchive Zi ...
- linux文件压缩解压命令
01-.tar格式解包:[*******]$ tar xvf FileName.tar打包:[*******]$ tar cvf FileName.tar DirName(注:tar是打包,不是压缩! ...
- Linux基础------文件打包解包---tar命令,文件压缩解压---命令gzip,vim编辑器创建和编辑正文件,磁盘分区/格式化,软/硬链接
作业一:1) 将用户信息数据库文件和组信息数据库文件纵向合并为一个文件/1.txt(覆盖) cat /etc/passwd /etc/group > /1.txt2) 将用户信息数据库文件和用户 ...
- linux笔记:linux常用命令-压缩解压命令
压缩解压命令:gzip(压缩文件,不保留原文件.这个命令不能压缩目录) 压缩解压命令:gunzip(解压.gz的压缩文件) 压缩解压命令:tar(打包压缩目录或者解压压缩文件.打包的意思是把目录打包成 ...
- linux命令:压缩解压命令
压缩解压命令:gzip 命令名称:gzip 命令英文原意:GNU zip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip 选项 [文件] 功能描述:压缩文件 压缩后文件格式:g ...
随机推荐
- 分布式搜索elasticsearch配置文件详解
elasticsearch的config文件夹里面有两个配置文件:elasticsearch.yml和logging.yml,第一个是es的基本配置文件,第二个是日志配置文件,es也是使用log4j来 ...
- entityframework学习笔记--006-表拆分与实体拆分
1.1 拆分实体到多张表 假设你有如下表,如图6-1.Product表用于存储商品的字符类信息,ProductWebInfo用于存储商品的图片,两张表通过SKU关联.现在你想把两张表的信息整合到一个实 ...
- getRequestDispatcher()与sendRedirect()的区别
1.request.getRequestDispatcher()是请求转发,前后页面共享一个request ; response.sendRedirect()是重新定向,前后页面不是一个request ...
- wamp 服务器安装问题 及cmd常用命令 和 php mysql数据库常用cmd命令集
1 官网下载wamp软件包,根据提示安装 2 目录结构: wamp: bin/为套件目录 包括mysql apache php log 日志记录 alias 配置 apps 数据库 ...
- Cleave.js – 自动格式化表单输入框的文本内容
Cleave.js 有一个简单的目的:帮助你自动格式输入的文本内容. 这个想法是提供一个简单的方法来格式化您的输入数据以增加输入字段的可读性.通过使用这个库,您不需要编写任何正则表达式来控制输入文本的 ...
- swing with transformjs
Antecedent Facebook made a HTML5 game long time ago. The opening animation is a piece of software th ...
- (七)Transformation和action详解-Java&Python版Spark
Transformation和action详解 视频教程: 1.优酷 2.YouTube 什么是算子 算子是RDD中定义的函数,可以对RDD中的数据进行转换和操作. 算子分类: 具体: 1.Value ...
- 解决问题:无法对 System程序集 添加Fakes程序集
为了在单元测试中指定DateTime.Now的值,我采用Microsoft Fakes技术的Shim. 主要参考了园里的http://www.cnblogs.com/FreeDong/p/335311 ...
- JAVA NIO Scatter/Gather(矢量IO)
矢量IO=Scatter/Gather: 在多个缓冲区上实现一个简单的IO操作.减少或避免了缓冲区拷贝和系统调用(IO) write:Gather 数据从几个缓冲区顺序抽取并沿着通道发送,就好 ...
- JS原型链
JS作为发展了多年了对象语言,支持继承,和完全面向对象语言不同的是,JS依赖原型链来实现对象的继承. 首先JS的对象分两大类,函数对象和普通对象,每个对象均内置__proto__属性,在不人为赋值__ ...