该控件是使用csharp写的,因此可以直接在dotnet环境中引用,不需要注册。

利用 SharpZipLib方便地压缩和解压缩文件
最新版本的SharpZipLib(0.84)增加了很多新的功能,其中包括增加了FastZip类,这让我们可以非常方便地把一个目录压缩成一个压缩包,经测试可以很好地支持文件中包含中文以及空格的情况。

压缩:

  1. /// <summary>
  2. /// 创建Zip对象
  3. /// </summary>
  4. /// <param name="filename">文件名.</param>
  5. /// <param name="directory">将要压缩的目录.</param>
  6. public static void ZipFile(string filename, string directory)
  7. {
  8. try
  9. {
  10. FastZip fz = new FastZip();
  11. fz.CreateEmptyDirectories = true;
  12. fz.CreateZip(filename, directory, true, "");
  13. fz = null;
  14. }
  15. catch (Exception)
  16. {
  17. throw;
  18. }
  19. }

解压缩:

  1. /// <summary>
  2. /// 解压缩.
  3. /// </summary>
  4. /// <param name="file">文件.</param>
  5. /// <returns>解压成功返回true,否则false</returns>
  6. public static bool UnpackFiles(string file, string dir)
  7. {
  8. try
  9. {
  10. if (!Directory.Exists(dir))
  11. Directory.CreateDirectory(dir);
  12.  
  13. ZipInputStream s = new ZipInputStream(File.OpenRead(file));
  14.  
  15. ZipEntry theEntry;
  16. while ((theEntry = s.GetNextEntry()) != null)
  17. {
  18.  
  19. string directoryName = Path.GetDirectoryName(theEntry.Name);
  20. string fileName = Path.GetFileName(theEntry.Name);
  21.  
  22. if (directoryName != String.Empty)
  23. Directory.CreateDirectory(dir + directoryName);
  24.  
  25. if (fileName != String.Empty)
  26. {
  27. FileStream streamWriter = File.Create(dir + theEntry.Name);
  28.  
  29. int size = ;
  30. byte[] data = new byte[];
  31. while (true)
  32. {
  33. size = s.Read(data, , data.Length);
  34. if (size > )
  35. {
  36. streamWriter.Write(data, , size);
  37. }
  38. else
  39. {
  40. break;
  41. }
  42. }
  43.  
  44. streamWriter.Close();
  45. }
  46. }
  47. s.Close();
  48. return true;
  49. }
  50. catch (Exception)
  51. {
  52. throw;
  53. }
  54. }

以下是SharpZipLib的另一种方法,其中方法全:

  1. /// <summary>
  2. /// 压缩和解压文件
  3. /// </summary>
  4. public class ZipClass
  5. {
  6. /// <summary>
  7. /// 所有文件缓存
  8. /// </summary>
  9. List<string> files = new List<string>();
  10.  
  11. /// <summary>
  12. /// 所有空目录缓存
  13. /// </summary>
  14. List<string> paths = new List<string>();
  15.  
  16. /// <summary>
  17. /// 压缩单个文件
  18. /// </summary>
  19. /// <param name="fileToZip">要压缩的文件</param>
  20. /// <param name="zipedFile">压缩后的文件全名</param>
  21. /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
  22. /// <param name="blockSize">分块大小</param>
  23. public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
  24. {
  25. if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
  26. {
  27. throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
  28. }
  29.  
  30. FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
  31. FileStream zipFile = File.Create(zipedFile);
  32. ZipOutputStream zipStream = new ZipOutputStream(zipFile);
  33. ZipEntry zipEntry = new ZipEntry(fileToZip);
  34. zipStream.PutNextEntry(zipEntry);
  35. zipStream.SetLevel(compressionLevel);
  36. byte[] buffer = new byte[blockSize];
  37. int size = streamToZip.Read(buffer, , buffer.Length);
  38. zipStream.Write(buffer, , size);
  39.  
  40. try
  41. {
  42. while (size < streamToZip.Length)
  43. {
  44. int sizeRead = streamToZip.Read(buffer, , buffer.Length);
  45. zipStream.Write(buffer, , sizeRead);
  46. size += sizeRead;
  47. }
  48. }
  49. catch (Exception ex)
  50. {
  51. GC.Collect();
  52. throw ex;
  53. }
  54.  
  55. zipStream.Finish();
  56. zipStream.Close();
  57. streamToZip.Close();
  58. GC.Collect();
  59. }
  60.  
  61. /// <summary>
  62. /// 压缩目录(包括子目录及所有文件)
  63. /// </summary>
  64. /// <param name="rootPath">要压缩的根目录</param>
  65. /// <param name="destinationPath">保存路径</param>
  66. /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
  67. public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)
  68. {
  69. GetAllDirectories(rootPath);
  70.  
  71. /* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾
  72. {
  73.  
  74. rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\"
  75.  
  76. }
  77. */
  78. //string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
  79. string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
  80. Crc32 crc = new Crc32();
  81. ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));
  82. outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression
  83. foreach (string file in files)
  84. {
  85. FileStream fileStream = File.OpenRead(file);//打开压缩文件
  86. byte[] buffer = new byte[fileStream.Length];
  87. fileStream.Read(buffer, , buffer.Length);
  88. ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
  89. entry.DateTime = DateTime.Now;
  90. // set Size and the crc, because the information
  91. // about the size and crc should be stored in the header
  92. // if it is not set it is automatically written in the footer.
  93. // (in this case size == crc == -1 in the header)
  94. // Some ZIP programs have problems with zip files that don't store
  95. // the size and crc in the header.
  96. entry.Size = fileStream.Length;
  97. fileStream.Close();
  98. crc.Reset();
  99. crc.Update(buffer);
  100. entry.Crc = crc.Value;
  101. outPutStream.PutNextEntry(entry);
  102. outPutStream.Write(buffer, , buffer.Length);
  103. }
  104.  
  105. this.files.Clear();
  106.  
  107. foreach (string emptyPath in paths)
  108. {
  109. ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");
  110. outPutStream.PutNextEntry(entry);
  111. }
  112.  
  113. this.paths.Clear();
  114. outPutStream.Finish();
  115. outPutStream.Close();
  116. GC.Collect();
  117. }
  118.  
  119. /// <summary>
  120. /// 取得目录下所有文件及文件夹,分别存入files及paths
  121. /// </summary>
  122. /// <param name="rootPath">根目录</param>
  123. private void GetAllDirectories(string rootPath)
  124. {
  125. string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录
  126. foreach (string path in subPaths)
  127. {
  128. GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
  129. }
  130. string[] files = Directory.GetFiles(rootPath);
  131. foreach (string file in files)
  132. {
  133. this.files.Add(file);//将当前目录中的所有文件全名存入文件List
  134. }
  135. if (subPaths.Length == files.Length && files.Length == )//如果是空目录
  136. {
  137. this.paths.Add(rootPath);//记录空目录
  138. }
  139. }
  140.  
  141. /// <summary>
  142. /// 解压缩文件(压缩文件中含有子目录)
  143. /// </summary>
  144. /// <param name="zipfilepath">待解压缩的文件路径</param>
  145. /// <param name="unzippath">解压缩到指定目录</param>
  146. /// <returns>解压后的文件列表</returns>
  147. public List<string> UnZip(string zipfilepath, string unzippath)
  148. {
  149. //解压出来的文件列表
  150. List<string> unzipFiles = new List<string>();
  151.  
  152. //检查输出目录是否以“\\”结尾
  153. if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
  154. {
  155. unzippath += "\\";
  156. }
  157.  
  158. ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
  159. ZipEntry theEntry;
  160. while ((theEntry = s.GetNextEntry()) != null)
  161. {
  162. string directoryName = Path.GetDirectoryName(unzippath);
  163. string fileName = Path.GetFileName(theEntry.Name);
  164.  
  165. //生成解压目录【用户解压到硬盘根目录时,不需要创建】
  166. if (!string.IsNullOrEmpty(directoryName))
  167. {
  168. Directory.CreateDirectory(directoryName);
  169. }
  170.  
  171. if (fileName != String.Empty)
  172. {
  173. //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
  174. if (theEntry.CompressedSize == )
  175. break;
  176. //解压文件到指定的目录
  177. directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
  178. //建立下面的目录和子目录
  179. Directory.CreateDirectory(directoryName);
  180.  
  181. //记录导出的文件
  182. unzipFiles.Add(unzippath + theEntry.Name);
  183.  
  184. FileStream streamWriter = File.Create(unzippath + theEntry.Name);
  185.  
  186. int size = ;
  187. byte[] data = new byte[];
  188. while (true)
  189. {
  190. size = s.Read(data, , data.Length);
  191. if (size > )
  192. {
  193. streamWriter.Write(data, , size);
  194. }
  195. else
  196. {
  197. break;
  198. }
  199. }
  200. streamWriter.Close();
  201. }
  202. }
  203. s.Close();
  204. GC.Collect();
  205. return unzipFiles;
  206. }
  207. }

C#压缩打包文件的更多相关文章

  1. [转]C#压缩打包文件

    /// <summary> /// 压缩和解压文件 /// </summary> public class ZipClass { /// <summary> /// ...

  2. java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹

    一.简述 zip用于压缩和解压文件.使用到的类有:ZipEntry  ZipOutputStream 二.具体实现代码 package com.joyplus.test; import java.io ...

  3. asp.net C#压缩打包文件例子

    /// <summary> /// 压缩和解压文件 /// </summary> public class ZipClass { /// <summary> /// ...

  4. java.util.zip压缩打包文件总结二: ZIP解压技术

    一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: Checked ...

  5. SharePoint 压缩打包文件代码分享

    前言 最近碰到这样一个需求,用户需要批量打包下载sharepoint文档库中的文档,所以,就需要开发一个打包下载的服务. 然后,把打包的代码分享给大家,也许会有需要的人. static void Ma ...

  6. linux文件压缩与文件夹压缩(打包)

    目录 一:linux文件压缩 1.linux常见的压缩包有哪些? 2.bzip压缩(文件) 二:打包(文件夹压缩) 1.打包命令 2.参数 3.参数解析(实战) 4.注意事项 简介: win中的压缩包 ...

  7. C# 压缩打包文件下载

    C# 压缩打包文件下载 public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform { #region INam ...

  8. albert1017 Linux下压缩某个文件夹(文件夹打包)

    albert1017 Linux下压缩某个文件夹(文件夹打包) tar -zcvf /home/xahot.tar.gz /xahottar -zcvf 打包后生成的文件名全路径 要打包的目录例子:把 ...

  9. Linux中的文件压缩,打包和备份命令

    压缩解压命令 gzip  文件   -c : 将压缩数据输出到屏幕,可用来重定向 -v   显示压缩比等信息 -d   解压参数 -t    用来检验一个压缩文件的一致性看看档案有没错 -数字 : 压 ...

随机推荐

  1. socket发送、接收信息----UDP

    # 导入套接字包 import socket def welcome(): print("------欢迎进入UDP聊天器--------") print("1.发送信息 ...

  2. python中的lambda()函数

    语句:print map(lambda x:x ** 2,[1,2,3,4,5]) 其中lambda()函数在Python文档,文档中解释如下: lambda An anonymous inline ...

  3. require sqlite3时报The specified module could not be found.错误

    http://dependencywalker.com/ 在这个站点下载对应平台的Dependency Walker,打开你自己编译好的.node文件(sqlite3\lib\binding\node ...

  4. [bzoj 2693] jzptab & [bzoj 2154] Crash的数字表格 (莫比乌斯反演)

    题目描述 TTT组数据,给出NNN,MMM,求∑x=1N∑y=1Mlim(x,y)\sum_{x=1}^N\sum_{y=1}^M lim(x,y)\newlinex=1∑N​y=1∑M​lim(x, ...

  5. 微信&QQ中打开网页提示“已停止访问该网页”是怎么回事?

    背景 大家是不是经常会遇到这种情况,分享出去的网页链接在微信里或者QQ里打开会提示“已停止访问该网页”,当大家看到这种的提示的时候就说明你访问的网页已经被腾讯拦截了. 当大家遇到以上这种情况的时候要怎 ...

  6. HTML 003 元素

    HTML 元素 HTML 文档由 HTML 元素定义. HTML 元素 开始标签 * 元素内容 结束标签 * <p> 这是一个段落 </p> <a href=" ...

  7. loj #2319

    noip2017列队 - resolve 标签:题解 \(n * m\) 的矩阵,每个元素 \((i, j)\) 的标号为 \((i - 1) * m + j\), 每次给出 \((x, y)\), ...

  8. 01.Flink笔记-编译、部署

    Flink开发环境部署配置 Flink是一个以Java及Scala作为开发语言的开源大数据项目,代码开源在github上,并使用maven来编译和构建项目.所需工具:Java.maven.Git. 本 ...

  9. ROS常用命令

    ROS常用命令 打印ros环境变量 $ echo $ROS_PACKAGE_PATH 确认环境变量已经设置正确 export | grep ROS 环境变量设置文件 sudo gedit ./.bas ...

  10. SpringCloud介绍及入门一

    springcloud是什么 基于spring boot实现的服务治理工具包,管理和协微服务 把别人的东西拿来组合在一起,形成各种组件 微服务协调者[service registtry注册中心 Eur ...