接口

  1. public interface IUnZip
  2. {
  3. /// <summary>
  4. /// 功能:解压zip格式的文件。
  5. /// </summary>
  6. /// <param name="zipFilePath">压缩文件路径</param>
  7. /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
  8. /// <param name="password">压缩包密码</param>
  9. /// <returns>解压后文件所在的文件夹</returns>
  10. string UnZipFile(string zipFilePath, string unZipDir = null, string password = null);
  11. }
  12. public interface IZip
  13. {
  14. /// <summary>
  15. /// 将选定的文件压入一个目标zip中
  16. /// </summary>
  17. /// <param name="list">选定的文件/文件夹(路径的集合)</param>
  18. /// <param name="targetFileName">压缩后得到的zip保存路径</param>
  19. /// <param name="password">压缩包密码</param>
  20. /// <param name="overwrite">如果Zip文件已存在,是否覆盖</param>
  21. /// <param name="level">压缩等级0—9</param>
  22. /// <returns>压缩包路径</returns>
  23. void Compress(List<string> list, string targetFileName, string password = null, bool overwrite = true, int level = 9);
  24. /// <summary>
  25. /// 将选定的文件压入一个目标zip中
  26. /// </summary>
  27. /// <param name="fileOrDir">选定的文件/文件夹</param>
  28. /// <param name="targetFileName">压缩后得到的zip保存路径</param>
  29. /// <param name="password">压缩包密码</param>
  30. /// <param name="overwrite">如果Zip文件已存在,是否覆盖</param>
  31. /// <param name="level">压缩等级0—9</param>
  32. /// <returns>压缩包路径</returns>
  33. void Compress(string fileOrDir, string targetFileName, string password = null, bool overwrite = true, int level = 9);
  34. }
  35. public interface IZipHelper:IZip,IUnZip
  36. {
  37. }

实现

  1. public class ZipHelper : IZipHelper
  2. {
  3. #region 压缩文件
  4. /// <inheritdoc/>
  5. public void Compress(string fileOrDir, string targetFileName, string password = null, bool overwrite = true, int level = 9)
  6. {
  7. List<string> list = new List<string> { fileOrDir };
  8. Compress(list, targetFileName, password, overwrite,level);
  9. }
  10. /// <inheritdoc/>
  11. public void Compress(List<string> list, string targetFileName, string password = null, bool overwrite = true,int level = 9)
  12. {
  13. CheckForCompress(list, targetFileName, overwrite);
  14. //如果已经存在目标文件,删除
  15. if (File.Exists(targetFileName))
  16. {
  17. File.Delete(targetFileName);
  18. }
  19. ZipOutputStream zips = null;
  20. FileStream fileStream = null;
  21. try
  22. {
  23. fileStream = File.Create(targetFileName);
  24. zips = new ZipOutputStream(fileStream);
  25. zips.SetLevel(level % 10); //压缩等级
  26. zips.Password = password;
  27. foreach (string dir in list)
  28. {
  29. if (File.Exists(dir))
  30. {
  31. AddFile("",dir, zips);
  32. }
  33. else
  34. {
  35. CompressFolder("", dir, zips);
  36. }
  37. }
  38. zips.Finish();
  39. }
  40. catch { throw; }
  41. finally
  42. {
  43. if(fileStream!= null)
  44. {
  45. fileStream.Close();
  46. fileStream.Dispose();
  47. }
  48. if(zips!= null)
  49. {
  50. zips.Close();
  51. zips.Dispose();
  52. }
  53. }
  54. }
  55. #region private
  56. private void CheckForCompress(List<string> files, string targetFileName, bool overwrite)
  57. {
  58. //因为files可能来自不同的文件夹,所以不方便自动提供一个默认文件夹,需要提供
  59. if (!overwrite && File.Exists(targetFileName))
  60. {
  61. throw new Exception("目标zip文件已存在!");
  62. }
  63. //待压入的文件或文件夹需要真实存在
  64. foreach (var item in files)
  65. {
  66. if (!File.Exists(item) && !Directory.Exists(item))
  67. {
  68. throw new Exception($"文件/文件夹【{item}】不存在!");
  69. }
  70. }
  71. //不能有同名的文件/文件夹
  72. Dictionary<string, string> dic = new Dictionary<string, string>();
  73. foreach (var item in files)
  74. {
  75. string item_ = item.TrimEnd('/', '\\');
  76. string fileName = Path.GetFileName(item_);
  77. if (dic.ContainsKey(fileName))
  78. {
  79. throw new Exception($"选中的文件/文件夹中存在同名冲突:【{dic[fileName]}】,【{item_}】");
  80. }
  81. else
  82. {
  83. dic[fileName] = item_;
  84. }
  85. }
  86. }
  87. private void AddFile(string orignalDir, string file, ZipOutputStream zips)
  88. {
  89. //文件
  90. FileStream StreamToZip = null;
  91. try
  92. {
  93. //加入ZIP文件条目(为压缩文件流提供一个容器)
  94. StreamToZip = new FileStream(file, FileMode.Open, FileAccess.Read);
  95. string fileName = Path.GetFileName(file);
  96. if (!string.IsNullOrEmpty(orignalDir))
  97. {
  98. fileName = orignalDir + Path.DirectorySeparatorChar + fileName;
  99. }
  100. ZipEntry z = new ZipEntry(fileName);
  101. zips.PutNextEntry(z);
  102. //写入文件流
  103. int pack = 10240; //10Kb
  104. byte[] buffer = new byte[pack];
  105. int size = StreamToZip.Read(buffer, 0, buffer.Length);
  106. while (size > 0)
  107. {
  108. zips.Write(buffer, 0, size);
  109. size = StreamToZip.Read(buffer, 0, buffer.Length);
  110. }
  111. }
  112. catch { throw; }
  113. finally
  114. {
  115. if (StreamToZip != null)
  116. {
  117. StreamToZip.Close();
  118. StreamToZip.Dispose();
  119. }
  120. }
  121. }
  122. private void AddFolder(string orignalDir, string folder, ZipOutputStream zips)
  123. {
  124. //文件夹
  125. folder = folder.TrimEnd('/','\\');
  126. string fileName = Path.GetFileName(folder);
  127. if (!string.IsNullOrEmpty(orignalDir))
  128. {
  129. fileName = orignalDir + Path.DirectorySeparatorChar + fileName ;
  130. }
  131. fileName += Path.DirectorySeparatorChar;
  132. ZipEntry z = new ZipEntry(fileName);
  133. zips.PutNextEntry(z);
  134. }
  135. /// <summary>
  136. /// 递归压缩文件夹内所有文件和子文件夹
  137. /// </summary>
  138. /// <param name="orignalDir">外层文件夹</param>
  139. /// <param name="dir">被压缩文件夹</param>
  140. /// <param name="zips">流</param>
  141. private void CompressFolder(string orignalDir,string dir, ZipOutputStream zips)
  142. {
  143. // 压缩当前文件夹下所有文件
  144. string[] names = Directory.GetFiles(dir);
  145. foreach (string fileName in names)
  146. {
  147. AddFile(orignalDir,fileName, zips);
  148. }
  149. // 压缩子文件夹
  150. names = Directory.GetDirectories(dir);
  151. foreach (string folderName in names)
  152. {
  153. AddFolder(orignalDir, folderName, zips);
  154. string _orignalDir = Path.GetFileName(folderName);
  155. if (!string.IsNullOrEmpty(orignalDir))
  156. {
  157. _orignalDir = orignalDir + Path.DirectorySeparatorChar + _orignalDir;
  158. }
  159. CompressFolder(_orignalDir, folderName, zips);
  160. }
  161. }
  162. #endregion private
  163. #endregion 压缩文件
  164. #region 解压文件
  165. /// <inheritdoc/>
  166. public string UnZipFile(string zipFilePath, string unZipDir = null,string password = null)
  167. {
  168. if (!File.Exists(zipFilePath))
  169. {
  170. throw new Exception($"压缩文件【{zipFilePath}】不存在!");
  171. }
  172. //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
  173. if (string.IsNullOrWhiteSpace(unZipDir))
  174. {
  175. unZipDir = Path.GetDirectoryName(zipFilePath);
  176. string name = Path.GetFileNameWithoutExtension(zipFilePath);
  177. unZipDir = Path.Combine(unZipDir, name);
  178. }
  179. string unZipDir2 = unZipDir;
  180. char lastChar = unZipDir[unZipDir.Length - 1];
  181. if (lastChar != '/' && lastChar != '\\')
  182. {
  183. unZipDir += Path.DirectorySeparatorChar;
  184. }
  185. if (!Directory.Exists(unZipDir))
  186. Directory.CreateDirectory(unZipDir);
  187. //解压
  188. UnZipProcess(zipFilePath, unZipDir, password);
  189. return unZipDir2;
  190. }
  191. private void UnZipProcess(string zipFilePath, string unZipDir, string password)
  192. {
  193. ZipInputStream zipInput = null;
  194. FileStream fileStream = null;
  195. try
  196. {
  197. fileStream = File.OpenRead(zipFilePath);
  198. zipInput = new ZipInputStream(fileStream);
  199. zipInput.Password = password;
  200. ZipEntry theEntry;
  201. while ((theEntry = zipInput.GetNextEntry()) != null)
  202. {
  203. string tempPath = unZipDir + theEntry.Name;
  204. if (theEntry.IsDirectory)
  205. {
  206. if (!Directory.Exists(tempPath))
  207. {
  208. Directory.CreateDirectory(tempPath);
  209. }
  210. }
  211. else
  212. {
  213. using (FileStream streamWriter = File.Create(tempPath))
  214. {
  215. byte[] buffer = new byte[10240];
  216. int size = zipInput.Read(buffer, 0, buffer.Length);
  217. while (size > 0)
  218. {
  219. streamWriter.Write(buffer, 0, size);
  220. size = zipInput.Read(buffer, 0, buffer.Length);
  221. }
  222. }
  223. }
  224. }
  225. }
  226. catch
  227. {
  228. throw;
  229. }
  230. finally
  231. {
  232. if (fileStream != null)
  233. {
  234. fileStream.Close();
  235. fileStream.Dispose();
  236. }
  237. if (zipInput != null)
  238. {
  239. zipInput.Close();
  240. zipInput.Dispose();
  241. }
  242. }
  243. }
  244. #endregion
  245. }

使用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. 从ASP.NET 升级到ASP.NET5(RC1) - 翻译

    前言 ASP.NET 5 是一次令人惊叹的对于ASP.NET的创新革命. 他将构建目标瞄准了 .NET Core CLR, 同时ASP.NET又是对于云服务进行优化,并且是跨平台的框架.很多文章已经称 ...

  2. python 数据类型---列表使用 之二 (增删改查)

    列表的操作 1.列表的修改 >>> name ['Frank', 'Lee', 2, ['Andy', 'Troy']] >>> name[0] = "F ...

  3. SSH框架和Redis的整合(1)

    一个已有的Struts+Spring+Hibernate项目,以前使用MySQL数据库,现在想把Redis也整合进去. 1. 相关Jar文件 下载并导入以下3个Jar文件: commons-pool2 ...

  4. c++ builder 2010 错误 F1004 Internal compiler error at 0x9740d99 with base 0x9

    今天遇到一个奇怪的问题,拷贝项目后,在修改,会出现F1004 Internal compiler error at 0x9740d99 with base 0x9 ,不管怎么改,删除改动,都没用,关闭 ...

  5. JVM调优总结

    堆大小设置JVM 中最大堆大小有三方面限制:相关操作系统的数据模型(32-bt还是64-bit)限制:系统的可用虚拟内存限制:系统的可用物理内存限制.32位系统下,一般限制在1.5G~2G:64为操作 ...

  6. QT数据库连接的几个重要函数的使用及注意事项(原创)

    注:在这里数据库对象等同于数据库连接对象,也就是QSqlDatabase类的对象 QSqlDatabase QSqlDatabase::addDatabase((const QString & ...

  7. Css3新特性总结之边框与背景(二)

    一.条纹背景 利用background为linear-gradient函数实现,linear-gradient取值如下: <angle>:角度,渐变的方向 to left right to ...

  8. JS高程5.引用类型(2)Array类型

    Array类型: ECMAScript数组的每一项可以保存任何类型的数据,数组的大小是可以动态调整的. 创建数组的基本方式: (1)使用Array构造函数 var color=new Array(); ...

  9. C++01.类的引入

    1.假设我们要输出张三,李四两个人的基本信息,包括姓名,年龄,可以用以下的C程序实现: eg: #include <stdio.h> int main(int argc,char **ar ...

  10. Allocators与Criterion的相同点及区别

    C++98: 1.相同点: Allocators having the same type were assumed to be equal so that memory allocated by o ...