接口

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实现文件压缩、解压的更多相关文章

  1. 使用SharpZIpLib写的压缩解压操作类

    使用SharpZIpLib写的压缩解压操作类,已测试. public class ZipHelper { /// <summary> /// 压缩文件 /// </summary&g ...

  2. Linux 之 文件压缩解压

    文件压缩解压 参考教程:[千峰教育] 命令: gzip: 作用:压缩文件,只能是单个文件,不能是多个,也不能是目录. 格式:gzip file 说明:执行命令会生成file.gz,删除原来的file ...

  3. linux驱动系列之文件压缩解压小节(转)

    转至网页:http://www.jb51.net/LINUXjishu/43356.html Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通 ...

  4. 分享一个ASP.NET 文件压缩解压类 C#

    需要引用一个ICSharpCode.SharpZipLib.dll using System; using System.Collections.Generic; using System.Linq; ...

  5. C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用

    工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个 ...

  6. iOS - File Archive/UnArchive 文件压缩/解压

    1.ZipArchive 方式 ZipArchive 只能对 zip 类文件进行压缩和解压缩 GitHub 网址:https://github.com/ZipArchive/ZipArchive Zi ...

  7. linux文件压缩解压命令

    01-.tar格式解包:[*******]$ tar xvf FileName.tar打包:[*******]$ tar cvf FileName.tar DirName(注:tar是打包,不是压缩! ...

  8. Linux基础------文件打包解包---tar命令,文件压缩解压---命令gzip,vim编辑器创建和编辑正文件,磁盘分区/格式化,软/硬链接

    作业一:1) 将用户信息数据库文件和组信息数据库文件纵向合并为一个文件/1.txt(覆盖) cat /etc/passwd /etc/group > /1.txt2) 将用户信息数据库文件和用户 ...

  9. linux笔记:linux常用命令-压缩解压命令

    压缩解压命令:gzip(压缩文件,不保留原文件.这个命令不能压缩目录) 压缩解压命令:gunzip(解压.gz的压缩文件) 压缩解压命令:tar(打包压缩目录或者解压压缩文件.打包的意思是把目录打包成 ...

  10. linux命令:压缩解压命令

    压缩解压命令:gzip 命令名称:gzip 命令英文原意:GNU zip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip 选项  [文件] 功能描述:压缩文件 压缩后文件格式:g ...

随机推荐

  1. sea.js详解

    Seajs相关知识 seajs.Use 引入入口文件 第一个参数表示模块id 字符串表示一个模块id 数组,数组每个成员表示一个模块 第二个参数表示回调函数(可有可无的) 作用就是当模块加载完成执行回 ...

  2. 《Web开发中让盒子居中的几种方法》

    一.记录下几种盒子居中的方法: 1.0.margin固定宽高居中: 2.0.负margin居中: 3.0.绝对定位居中: 4.0.table-cell居中: 5.0.flex居中: 6.0.trans ...

  3. iOS之数字的格式化

    //通过NSNumberFormatter,同样可以设置NSNumber输出的格式.例如如下代码: NSNumberFormatter *formatter = [[NSNumberFormatter ...

  4. pip安装指定版本的package

    起因 最近到一个项目组,用了一套高大上的运维工具来搭建开发环境. 有vagrant控制VirtualBox启动虚拟机.有ansible来运行playbook初始化环境. 然后遇到了一个坑,项目现有的p ...

  5. Time Consume Problem

    I joined the NodeJS online Course three weeks ago, but now I'm late about 2 weeks. I pay the codesch ...

  6. GDB调试命令小结

    1.启动调试 前置条件:编译生成执行码时带上 -g,如果使用Makefile,通过给CFLAGS指定-g选项,否则调试时没有符号信息.gdb program //最常用的用gdb启动程序,开始调试的方 ...

  7. Python中对时间日期的处理方法简单汇总

    这篇文章主要介绍了Python实用日期时间处理方法汇总,本文讲解了获取当前datetime.获取当天date.获取明天/前N天.获取当天开始和结束时间(00:00:00 23:59:59).获取两个d ...

  8. 关于SQL Server镜像的一个小误区

    昨天晚上突然接到客户的电话, 说在配置了镜像的生产环境数据库下修改 “已提交读快照” 选项的时候报错, 需要先取消镜像然后再重新搭建.悲催的是这是个近TB的数据库,问我有没有什么快速的方法.于是我就问 ...

  9. [Android] 怎么在应用中实现密码隐藏?

    [Android] 怎么在应用中实现密码隐藏? 在安卓应用中,用户注册或者登录时,需要把密码隐藏,实现一定的保密效果.在安卓中,可以通过设置EditText组件的TransformationMetho ...

  10. Python学习笔记8-单元测试(1)

    源代码: roman_mumeral_map = (('M',1000), ('CM',900), ('D',500), ('CD',400), ('C',100), ('XC',90), ('L', ...