需要引用一个ICSharpCode.SharpZipLib.dll

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using ICSharpCode.SharpZipLib.Zip;
  6. using System.IO;
  7. using ICSharpCode.SharpZipLib.Checksums;
  8. using System.Web;
  9. namespace Mvc51Hiring.Common.Tool
  10. {
  11. /// <summary>
    /// 作者:来自网格
    /// 修改人:sunkaixaun
  12. /// 压缩和解压文件
  13. /// </summary>
  14. public class ZipClass
  15. {
  16. /// <summary>
  17. /// 所有文件缓存
  18. /// </summary>
  19. List<string> files = new List<string>();
  20.  
  21. /// <summary>
  22. /// 所有空目录缓存
  23. /// </summary>
  24. List<string> paths = new List<string>();
  25.  
  26. /// <summary>
  27. /// 压缩单个文件根据文件地址
  28. /// </summary>
  29. /// <param name="fileToZip">要压缩的文件</param>
  30. /// <param name="zipedFile">压缩后的文件全名</param>
  31. /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
  32. /// <param name="blockSize">分块大小</param>
  33. public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
  34. {
  35. if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
  36. {
  37. throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
  38. }
  39.  
  40. FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
  41. FileStream zipFile = File.Create(zipedFile);
  42. ZipOutputStream zipStream = new ZipOutputStream(zipFile);
  43. ZipEntry zipEntry = new ZipEntry(fileToZip);
  44. zipStream.PutNextEntry(zipEntry);
  45. zipStream.SetLevel(compressionLevel);
  46. byte[] buffer = new byte[blockSize];
  47. int size = streamToZip.Read(buffer, 0, buffer.Length);
  48. zipStream.Write(buffer, 0, size);
  49.  
  50. try
  51. {
  52. while (size < streamToZip.Length)
  53. {
  54. int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
  55. zipStream.Write(buffer, 0, sizeRead);
  56. size += sizeRead;
  57. }
  58. }
  59. catch (Exception ex)
  60. {
  61. GC.Collect();
  62. throw ex;
  63. }
  64.  
  65. zipStream.Finish();
  66. zipStream.Close();
  67. streamToZip.Close();
  68. GC.Collect();
  69. }
  70.  
  71. /// <summary>
  72. /// 压缩目录(包括子目录及所有文件)
  73. /// </summary>
  74. /// <param name="rootPath">要压缩的根目录</param>
  75. /// <param name="destinationPath">保存路径</param>
  76. /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
  77. public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)
  78. {
  79. GetAllDirectories(rootPath);
  80.  
  81. /* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾
  82. {
  83.  
  84. rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\"
  85.  
  86. }
  87. */
  88. //string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
  89. string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
  90. Crc32 crc = new Crc32();
  91. ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));
  92. outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression
  93. foreach (string file in files)
  94. {
  95. FileStream fileStream = File.OpenRead(file);//打开压缩文件
  96. byte[] buffer = new byte[fileStream.Length];
  97. fileStream.Read(buffer, 0, buffer.Length);
  98. ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
  99. entry.DateTime = DateTime.Now;
  100. // set Size and the crc, because the information
  101. // about the size and crc should be stored in the header
  102. // if it is not set it is automatically written in the footer.
  103. // (in this case size == crc == -1 in the header)
  104. // Some ZIP programs have problems with zip files that don't store
  105. // the size and crc in the header.
  106. entry.Size = fileStream.Length;
  107. fileStream.Close();
  108. crc.Reset();
  109. crc.Update(buffer);
  110. entry.Crc = crc.Value;
  111. outPutStream.PutNextEntry(entry);
  112. outPutStream.Write(buffer, 0, buffer.Length);
  113. }
  114.  
  115. this.files.Clear();
  116.  
  117. foreach (string emptyPath in paths)
  118. {
  119. ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");
  120. outPutStream.PutNextEntry(entry);
  121. }
  122.  
  123. this.paths.Clear();
  124. outPutStream.Finish();
  125. outPutStream.Close();
  126. GC.Collect();
  127. }
  128.  
  129. /// <summary>
  130. /// 多文件打包下载
  131. /// </summary>
  132. public void DwonloadZip(string[] filePathList, string zipName)
  133. {
  134.  
  135. MemoryStream ms = new MemoryStream();
  136. byte[] buffer = null;
  137. var context = HttpContext.Current;
  138. using (ICSharpCode.SharpZipLib.Zip.ZipFile file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms))
  139. {
  140. file.BeginUpdate();
  141. file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
  142. foreach (var it in filePathList)
  143. {
  144. file.Add(context.Server.MapPath(it));
  145. }
  146. file.CommitUpdate();
  147.  
  148. buffer = new byte[ms.Length];
  149. ms.Position = 0;
  150. ms.Read(buffer, 0, buffer.Length);
  151. }
  152. context.Response.AddHeader("content-disposition", "attachment;filename=" + zipName);
  153. context.Response.BinaryWrite(buffer);
  154. context.Response.Flush();
  155. context.Response.End();
  156. }
  157.  
  158. /// <summary>
  159. /// 取得目录下所有文件及文件夹,分别存入files及paths
  160. /// </summary>
  161. /// <param name="rootPath">根目录</param>
  162. private void GetAllDirectories(string rootPath)
  163. {
  164. string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录
  165. foreach (string path in subPaths)
  166. {
  167. GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
  168. }
  169. string[] files = Directory.GetFiles(rootPath);
  170. foreach (string file in files)
  171. {
  172. this.files.Add(file);//将当前目录中的所有文件全名存入文件List
  173. }
  174. if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录
  175. {
  176. this.paths.Add(rootPath);//记录空目录
  177. }
  178. }
  179.  
  180. /// <summary>
  181. /// 解压缩文件(压缩文件中含有子目录)
  182. /// </summary>
  183. /// <param name="zipfilepath">待解压缩的文件路径</param>
  184. /// <param name="unzippath">解压缩到指定目录</param>
  185. /// <returns>解压后的文件列表</returns>
  186. public List<string> UnZip(string zipfilepath, string unzippath)
  187. {
  188. //解压出来的文件列表
  189. List<string> unzipFiles = new List<string>();
  190.  
  191. //检查输出目录是否以“\\”结尾
  192. if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
  193. {
  194. unzippath += "\\";
  195. }
  196.  
  197. ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
  198. ZipEntry theEntry;
  199. while ((theEntry = s.GetNextEntry()) != null)
  200. {
  201. string directoryName = Path.GetDirectoryName(unzippath);
  202. string fileName = Path.GetFileName(theEntry.Name);
  203.  
  204. //生成解压目录【用户解压到硬盘根目录时,不需要创建】
  205. if (!string.IsNullOrEmpty(directoryName))
  206. {
  207. Directory.CreateDirectory(directoryName);
  208. }
  209.  
  210. if (fileName != String.Empty)
  211. {
  212. //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
  213. if (theEntry.CompressedSize == 0)
  214. break;
  215. //解压文件到指定的目录
  216. directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
  217. //建立下面的目录和子目录
  218. Directory.CreateDirectory(directoryName);
  219.  
  220. //记录导出的文件
  221. unzipFiles.Add(unzippath + theEntry.Name);
  222.  
  223. FileStream streamWriter = File.Create(unzippath + theEntry.Name);
  224.  
  225. int size = 2048;
  226. byte[] data = new byte[2048];
  227. while (true)
  228. {
  229. size = s.Read(data, 0, data.Length);
  230. if (size > 0)
  231. {
  232. streamWriter.Write(data, 0, size);
  233. }
  234. else
  235. {
  236. break;
  237. }
  238. }
  239. streamWriter.Close();
  240. }
  241. }
  242. s.Close();
  243. GC.Collect();
  244. return unzipFiles;
  245. }
  246. }
  247. public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
  248. {
  249.  
  250. #region INameTransform 成员
  251.  
  252. public string TransformDirectory(string name)
  253. {
  254. return null;
  255. }
  256.  
  257. public string TransformFile(string name)
  258. {
  259. return Path.GetFileName(name);
  260. }
  261.  
  262. #endregion
  263. }
  264. }

  

分享一个ASP.NET 文件压缩解压类 C#的更多相关文章

  1. Linux 之 文件压缩解压

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

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

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

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

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

  4. linux文件压缩解压命令

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

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

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

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

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

  7. 基于哈夫曼编码的压缩解压程序(C 语言)

    这个程序是研一上学期的课程大作业.当时,跨专业的我只有一点 C 语言和数据结构基础,为此,我查阅了不少资料,再加上自己的思考和分析,实现后不断调试.测试和完善,耗时一周左右,在 2012/11/19 ...

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

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

  9. c#自带压缩类实现的多文件压缩和解压

    用c#自带的System.IO.Compression命名空间下的压缩类实现的多文件压缩和解压功能,缺点是多文件压缩包的解压只能调用自身的解压方法,和现有的压缩软件不兼容.下面的代码没有把多文件的目录 ...

随机推荐

  1. hibernate spring annotation setup

    First step setup for the pom.xml with hibernate dependency , hibernate dependency need to before the ...

  2. 基于JQuery.timer插件实现一个计时器

    基于JQuery.timer插件实现一个计时器,需要的朋友可以参考下.   先去官网下载jQuery Timers插件 ,然后引用到html中.这里是1.2 version 复制代码代码如下: < ...

  3. 面包板入门电子制作(class1)视频 全套30集高清

    面包板入门电子制作(class1)套件(30集高清) 本套件以电子制作中最基础的元器件在面包板上搭建电路,用启发性的视频教学方式,使学习者熟悉电子电路基础.发挥想像力.在创新设计和制作中学会独立设计和 ...

  4. Android 使用java.net.socket 的接收问题

    // 初始化socketsocket = new Socket(InetAddress.getByName(sip), sport);InputStream sin = socket.getInput ...

  5. eclipse maven 创建总POM 工程

    首先进入到eclipse的workspace,我这里的workspace目录是D:\workspace 1.创建总的POM D:\workspace>mvn archetype:create - ...

  6. 数据标准化 Normalization

    数据的标准化(normalization)是将数据按比例缩放,使之落入一个小的特定区间.在某些比较和评价的指标处理中经常会用到,去除数据的单位限制,将其转化为无量纲的纯数值,便于不同单位或量级的指标能 ...

  7. 统一回复《怎么学JavaScript?》

    作者:小不了链接:https://zhuanlan.zhihu.com/p/23265155来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 鉴于时不时,有同学私信问我( ...

  8. 聊聊CSS postproccessors

      阿里妈妈 @一丝 准备发布其CSSGrace,即CSS后处理插件,于是顺便聊聊CSS postprocessors. 从Rework说起 Rework是TJ大神开发的CSS预处理框架.但为什么会出 ...

  9. spring之ControllerAdvice注解

    @ControllerAdvice是Spring 3.2新增的注解,主要是用来Controller的一些公共的需求的低侵入性增强提供辅助,作用于@RequestMapping标注的方法上. Contr ...

  10. How to set colors of HTML tables

    There is a simple way to set the color of tables: use the bgcolor attribute of tag <table>.   ...