使用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 ...
随机推荐
- 从ASP.NET 升级到ASP.NET5(RC1) - 翻译
前言 ASP.NET 5 是一次令人惊叹的对于ASP.NET的创新革命. 他将构建目标瞄准了 .NET Core CLR, 同时ASP.NET又是对于云服务进行优化,并且是跨平台的框架.很多文章已经称 ...
- python 数据类型---列表使用 之二 (增删改查)
列表的操作 1.列表的修改 >>> name ['Frank', 'Lee', 2, ['Andy', 'Troy']] >>> name[0] = "F ...
- SSH框架和Redis的整合(1)
一个已有的Struts+Spring+Hibernate项目,以前使用MySQL数据库,现在想把Redis也整合进去. 1. 相关Jar文件 下载并导入以下3个Jar文件: commons-pool2 ...
- c++ builder 2010 错误 F1004 Internal compiler error at 0x9740d99 with base 0x9
今天遇到一个奇怪的问题,拷贝项目后,在修改,会出现F1004 Internal compiler error at 0x9740d99 with base 0x9 ,不管怎么改,删除改动,都没用,关闭 ...
- JVM调优总结
堆大小设置JVM 中最大堆大小有三方面限制:相关操作系统的数据模型(32-bt还是64-bit)限制:系统的可用虚拟内存限制:系统的可用物理内存限制.32位系统下,一般限制在1.5G~2G:64为操作 ...
- QT数据库连接的几个重要函数的使用及注意事项(原创)
注:在这里数据库对象等同于数据库连接对象,也就是QSqlDatabase类的对象 QSqlDatabase QSqlDatabase::addDatabase((const QString & ...
- Css3新特性总结之边框与背景(二)
一.条纹背景 利用background为linear-gradient函数实现,linear-gradient取值如下: <angle>:角度,渐变的方向 to left right to ...
- JS高程5.引用类型(2)Array类型
Array类型: ECMAScript数组的每一项可以保存任何类型的数据,数组的大小是可以动态调整的. 创建数组的基本方式: (1)使用Array构造函数 var color=new Array(); ...
- C++01.类的引入
1.假设我们要输出张三,李四两个人的基本信息,包括姓名,年龄,可以用以下的C程序实现: eg: #include <stdio.h> int main(int argc,char **ar ...
- Allocators与Criterion的相同点及区别
C++98: 1.相同点: Allocators having the same type were assumed to be equal so that memory allocated by o ...