生成ZIP压缩包C#代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. using ICSharpCode.SharpZipLib;
  6. using ICSharpCode.SharpZipLib.Checksums;
  7. using ICSharpCode.SharpZipLib.Zip;
  8. using System.IO;
  9. using log4net;
  10. using log4net.Config;
  11.  
  12. namespace Test.BLL
  13. {
  14. public class TestZipFile
  15. {
  16. protected static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  17.  
  18. ///<summary>
  19. /// 创建ZIP文件
  20. ///</summary>
  21. public void CreateZipFile(string[] files, string sTempFile, string sPassWord)
  22. {
  23. try
  24. {
  25. using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
  26. {
  27. s.SetLevel(); // 压缩级别 0-9
  28. if (sPassWord != "")
  29. {
  30. s.Password = sPassWord; //Zip压缩文件密码
  31. }
  32.  
  33. byte[] buffer = new byte[]; //缓冲区大小
  34.  
  35. foreach (string file in files)
  36. {
  37. if (!string.IsNullOrEmpty(file))
  38. {
  39. if (File.Exists(file))
  40. {
  41. ZipEntry entry = new ZipEntry(Path.GetFileName(file));
  42. entry.DateTime = DateTime.Now;
  43. s.PutNextEntry(entry);
  44.  
  45. using (FileStream fs = File.OpenRead(file))
  46. {
  47. int sourceBytes;
  48. do
  49. {
  50. sourceBytes = fs.Read(buffer, , buffer.Length);
  51. s.Write(buffer, , sourceBytes);
  52. } while (sourceBytes > );
  53. }
  54. }
  55. else
  56. {
  57. logger.Error("文件:" + file + "不存在。");
  58. }
  59. }
  60. }
  61.  
  62. s.Finish();
  63. s.Close();
  64. }
  65. }
  66. catch (Exception ex)
  67. {
  68. logger.Error("压缩文件时异常!");
  69. logger.Error("异常描述:\t" + ex.Message);
  70. logger.Error("异常方法:\t" + ex.TargetSite);
  71. logger.Error("异常堆栈:\t" + ex.StackTrace);
  72. }
  73. }
  74.  
  75. /// <summary>
  76. ///
  77. /// </summary>
  78. /// <param name="files">放入ZIP的文件路劲(含文件名)</param>
  79. /// <param name="sTempFile">创建的ZIP文件路劲(含文件名)</param>
  80. /// <param name="sPassWord">ZIP文件密码</param>
  81. /// <param name="folderNames">存放到ZIP中的文件夹名,空代表放在顶级目录</param>
  82. public void CreateZipFileMutilFolder(string[] files, string sTempFile, string sPassWord, string[] folderNames)
  83. {
  84. try
  85. {
  86. using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
  87. {
  88. s.SetLevel(); // 压缩级别 0-9
  89. if (sPassWord != "")
  90. {
  91. s.Password = sPassWord; //Zip压缩文件密码
  92. }
  93.  
  94. byte[] buffer = new byte[]; //缓冲区大小
  95.  
  96. int i = ;
  97. foreach (string file in files)
  98. {
  99. if (!string.IsNullOrEmpty(file))
  100. {
  101. if (File.Exists(file))
  102. {
  103. ZipEntry entry = new ZipEntry((string.IsNullOrEmpty(folderNames[i]) ? "" : (folderNames[i] + "\\")) + Path.GetFileName(file));
  104. entry.DateTime = DateTime.Now;
  105. s.PutNextEntry(entry);
  106.  
  107. using (FileStream fs = File.OpenRead(file))
  108. {
  109. int sourceBytes;
  110. do
  111. {
  112. sourceBytes = fs.Read(buffer, , buffer.Length);
  113. s.Write(buffer, , sourceBytes);
  114. } while (sourceBytes > );
  115. }
  116. }
  117. else
  118. {
  119. logger.Error("文件:" + file + "不存在。");
  120. }
  121. }
  122.  
  123. i++;
  124. }
  125.  
  126. s.Finish();
  127. s.Close();
  128. }
  129. }
  130. catch (Exception ex)
  131. {
  132. logger.Error("压缩文件时异常!");
  133. logger.Error("异常描述:\t" + ex.Message);
  134. logger.Error("异常方法:\t" + ex.TargetSite);
  135. logger.Error("异常堆栈:\t" + ex.StackTrace);
  136. }
  137. }
  138. }
  139. }

其中会用到的文件名、文件路径非法字符替换方法:

  1. /// <summary>
  2. /// Remove invalid characters which are not allowed in the file name
  3. /// </summary>
  4. /// <param name="fileName"></param>
  5. /// <returns></returns>
  6. public string RemoveFileNameInvalidChar(string fileName)
  7. {
  8. if (string.IsNullOrEmpty(fileName))
  9.  
  10. return fileName;
  11.  
  12. string invalidChars = new string(Path.GetInvalidFileNameChars());
  13.  
  14. string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars));
  15.  
  16. return Regex.Replace(fileName, invalidReStr, "");
  17.  
  18. }
  19.  
  20. /// <summary>
  21. /// Remove invalid characters which are not allowed in the path names
  22. /// </summary>
  23. /// <param name="filePath"></param>
  24. /// <returns></returns>
  25. public string RemovePathInvalidChar(string filePath)
  26. {
  27.  
  28. if (string.IsNullOrEmpty(filePath))
  29.  
  30. return filePath;
  31.  
  32. string invalidChars = new string(Path.GetInvalidPathChars());
  33.  
  34. string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars));
  35.  
  36. return Regex.Replace(filePath, invalidReStr, "");
  37.  
  38. }

参考:http://jianyun.org/archives/959.html

ZIP DLL:http://files.cnblogs.com/xuezhizhang/ICSharpCode.SharpZipLib.zip

C#生成ZIP压缩包的更多相关文章

  1. PHP生成zip压缩包

    /* * $res = new MakeZip($dir,$zipName); *@ $dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt' *@ $ ...

  2. 通过javascript在网页端生成zip压缩包并下载

    zip.js是什么 zip.js的github项目地址:http://gildas-lormeau.github.io/zip.js/ 通过zip.js封装一个能在网页端生成zip文件的插件, 直接在 ...

  3. 【java工具类】生成Zip压缩包

    多文件生成压缩包,返回压缩包生成位置的路径. FileUtil.java /** * 文件打压缩包 * @param files * @param Name * @return * @throws E ...

  4. python 生成zip压缩包

    import zipfile file_name="a.txt" f = zipfile.ZipFile('test.zip','w',zipfile.ZIP_STORED) f. ...

  5. php生成zip压缩文件的方法,支持文件和压缩包路径查找

    /* * new creatZip($_dir,$_zipName); *@ _dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt' *@ _zipN ...

  6. Node.js使用jszip实现打包zip压缩包

    一.前言 最近有这样的一个需求,需要把两个同名的.mtl文件和.obj文件打包成一个同名的.zip压缩包.刚开始文件不多的时候,只有几个,或者十几个,甚至二三十个的时候,还能勉强接受手动修改,但是随着 ...

  7. java生成zip压缩文件,解压缩文件

    1.生成zip public static void main(String[] args) { try { // testZip("c:\\temp.txt", "c: ...

  8. python 解压zip压缩包

    在当前路径解压zip压缩包,生成同名文件夹,内部目录结构与压缩包一致 import zipfile import os def un_zip(file_name): """ ...

  9. MySQL8.0 zip压缩包版本 Windows下安装

    MySQL zip压缩包版本 Windows下安装 Download MySQL Community Server 解压到相应的目录 我的解压目录:D:\Program Files\mysql-8.0 ...

随机推荐

  1. Ubuntu Apache 不同端口监听不同站点

    在/etc/apache2/apache2.conf 中,把项目根目录设置成默认的/var/www 不要设置在某个站点的路径下(我就是配置第一个站点时改了这里才会配置第二个站点时好久弄不出来) 在 / ...

  2. k-th smallest 问题总结

    k-th smallest/biggest 问题大约有这几道: 373. Find K Pairs with Smallest Sums 从两个list里各取一个数求和,求所有可能的sum里第k小的 ...

  3. Leeetcode--581. Shortest Unsorted Continuous Subarray

    Given an integer array, you need to find one continuous subarray that if you only sort this subarray ...

  4. CentOS添加明细路由

    网络架构图   根据最近为客户设计的网络架构,简单的梳理一个网路架构图,当然实际上的网络架构要比这个架构图复杂的多,咱们这边只是用这个图作为一个简单的示例. 拓扑分析   我们要实现专线两端不同网段的 ...

  5. kaldi的TIMIT实例二

    ============================================================================ MonoPhone Training & ...

  6. jdk-tomcat-jenkens 安装

    1--安装JDK 下载JDK放到你需要的目录,解压,然后添加环境变量 2--安装tomcat 从官方网站下载tomcat的安装包,然后解压 启动tomcat , TOMCAT的默认端口是8080,要记 ...

  7. Spring MVC & Boot & Cloud 技术教程汇总(长期更新)

    昨天我们发布了Java成神之路上的知识汇总,今天继续. Java成神之路技术整理(长期更新) 以下是Java技术栈微信公众号发布的关于 Spring/ Spring MVC/ Spring Boot/ ...

  8. HoloLens开发手记-配置开发环境 Install the tools

    随着Build 2016开发者大会的结束,HoloLens开发包也正式开放下载.Hololens没有独立的SDK,开发特性被集成到最新的Visual Studio Update 2中.如果你没有Hol ...

  9. 必须熟练的基础linux命令

    推荐:命令大全 http://man.linuxde.net/ 重要的几个热键[Tab],[ctrl]-c, [ctrl]-d [Tab]按键---具有『命令补全』不『档案补齐』的功能 [Ctrl]- ...

  10. JavaScript “跑马灯”抽奖活动代码解析与优化(二)

    既然是要编写插件.那么叫做"插件"的东西肯定是具有的某些特征能够满足我们平时开发的需求或者是提高我们的开发效率.那么叫做插件的东西应该具有哪些基本特征呢?让我们来总结一下: 1.J ...