递归实现压缩文件夹和子文件夹。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.IO.Compression;
  7. using System.Collections;
  8. using System.Runtime.Serialization;
  9. using System.Runtime.Serialization.Formatters.Binary;
  10.  
  11. namespace CommonBaseInfo
  12. {
  13. public class Zip
  14. {
  15.  
  16. #region 压缩解压单一文件
  17. /// <summary>
  18. /// 压缩单一文件
  19. /// </summary>
  20. /// <param name="sourceFile">源文件路径</param>
  21. /// <param name="destinationFile">目标文件路径</param>
  22. public static void CompressFile(string sourceFile, string destinationFile)
  23. {
  24. if (!File.Exists(sourceFile)) throw new FileNotFoundException();
  25. using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
  26. {
  27. byte[] buffer = new byte[sourceStream.Length];
  28. int checkCounter = sourceStream.Read(buffer, , buffer.Length);
  29. if (checkCounter != buffer.Length) throw new ApplicationException();
  30. using (FileStream destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write))
  31. {
  32. using (GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true))
  33. {
  34. compressedStream.Write(buffer, , buffer.Length);
  35. }
  36. }
  37. }
  38. }
  39. public static void CompressFile(byte[] source, string destinationFile)
  40. {
  41. using (FileStream destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write))
  42. {
  43. using (GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true))
  44. {
  45. compressedStream.Write(source, , source.Length);
  46. }
  47. }
  48. }
  49.  
  50. /// <summary>
  51. /// 解压缩文件
  52. /// </summary>
  53. /// <param name="sourceFile">源文件路径</param>
  54. /// <param name="destinationFile">目标文件路径</param>
  55. public static void DecompressFile(string sourceFile, string destinationFile)
  56. {
  57. if (!File.Exists(sourceFile)) throw new FileNotFoundException();
  58. using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open))
  59. {
  60. byte[] quartetBuffer = new byte[];
  61. int position = (int)sourceStream.Length - ;
  62. sourceStream.Position = position;
  63. sourceStream.Read(quartetBuffer, , );
  64. sourceStream.Position = ;
  65. int checkLength = BitConverter.ToInt32(quartetBuffer, );
  66. byte[] buffer = new byte[checkLength + ];
  67. using (GZipStream decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true))
  68. {
  69. int total = ;
  70. for (int offset = ; ; )
  71. {
  72. int bytesRead = decompressedStream.Read(buffer, offset, );
  73. if (bytesRead == ) break;
  74. offset += bytesRead;
  75. total += bytesRead;
  76. }
  77. using (FileStream destinationStream = new FileStream(destinationFile, FileMode.Create))
  78. {
  79. destinationStream.Write(buffer, , total);
  80. destinationStream.Flush();
  81. }
  82. }
  83. }
  84. }
  85.  
  86. #endregion
  87.  
  88. #region 压缩解压文件夹
  89. /**/
  90. /// <summary>
  91. /// 对目标文件夹进行压缩,将压缩结果保存为指定文件
  92. /// </summary>
  93. /// <param name="dirPath">目标文件夹</param>
  94. /// <param name="fileName">压缩文件</param>
  95. ///
  96.  
  97. public static void CompressFolderP(string dirPath, string fileName)
  98. {
  99. ArrayList list = new ArrayList();
  100. CompressFolder(dirPath, fileName, dirPath,list);
  101.  
  102. }
  103. public static void CompressFolder(string dirPath, string fileName, string rootdir, ArrayList list)
  104. {
  105.  
  106. foreach (string d in Directory.GetDirectories(dirPath))
  107. {
  108. byte[] destBuffer = null;
  109. string path = d.Replace(rootdir, "");
  110. SerializeFileInfo sfi = new SerializeFileInfo(d, destBuffer, "",path);
  111. list.Add(sfi);
  112. CompressFolder(d, fileName,rootdir,list);
  113.  
  114. }
  115.  
  116. foreach (string f in Directory.GetFiles(dirPath))
  117. { if ( (File.GetAttributes(f) & FileAttributes.Hidden) != FileAttributes.Hidden)
  118. {
  119. byte[] destBuffer = File.ReadAllBytes(f);
  120. string path = f.Replace(rootdir, "");
  121. SerializeFileInfo sfi = new SerializeFileInfo(f, destBuffer, "", path);
  122. list.Add(sfi);
  123. }
  124.  
  125. }
  126.  
  127. IFormatter formatter = new BinaryFormatter();
  128. using (Stream s = new MemoryStream())
  129. {
  130. formatter.Serialize(s, list);
  131. s.Position = ;
  132. CreateCompressFile(s, fileName);
  133. }
  134. }
  135. /**/
  136. /// <summary>
  137. /// 对目标压缩文件解压缩,将内容解压缩到指定文件夹
  138. /// </summary>
  139. /// <param name="fileName">压缩文件</param>
  140. /// <param name="dirPath">解压缩目录</param>
  141. ///
  142.  
  143. public static void DeCompressFolder(string fileName, string dirPath)
  144. {
  145.  
  146. if (!Directory.Exists(dirPath))
  147. {
  148. Directory.CreateDirectory(dirPath);
  149. }
  150.  
  151. using (Stream source = File.OpenRead(fileName))
  152. {
  153. using (Stream destination = new MemoryStream())
  154. {
  155. using (GZipStream input = new GZipStream(source, CompressionMode.Decompress, true))
  156. {
  157. byte[] bytes = new byte[];
  158. int n;
  159. while ((n = input.Read(bytes, , bytes.Length)) != )
  160. {
  161. destination.Write(bytes, , n);
  162. }
  163. }
  164. destination.Flush();
  165. destination.Position = ;
  166. DeSerializeFiles(destination, dirPath);
  167. }
  168. }
  169. }
  170. private static void DeSerializeFiles(Stream s, string dirPath)
  171. {
  172. BinaryFormatter b = new BinaryFormatter();
  173. ArrayList list = (ArrayList)b.Deserialize(s);
  174. foreach (SerializeFileInfo f in list)
  175. {
  176. if (f.Fileflag == "")
  177. {
  178. string newName = dirPath + f.Filedirnane;
  179. using (FileStream fs = new FileStream(newName, FileMode.Create, FileAccess.Write))
  180. {
  181. fs.Write(f.FileBuffer, , f.FileBuffer.Length);
  182. fs.Close();
  183. }
  184. }
  185. else
  186. {
  187. if (!Directory.Exists(dirPath+f.Filedirnane))
  188. {
  189. Directory.CreateDirectory(dirPath + f.Filedirnane);
  190. }
  191.  
  192. }
  193. }
  194. }
  195. private static void CreateCompressFile(Stream source, string destinationName)
  196. {
  197. using (Stream destination = new FileStream(destinationName, FileMode.Create, FileAccess.Write))
  198. {
  199. using (GZipStream output = new GZipStream(destination, CompressionMode.Compress))
  200. {
  201. byte[] bytes = new byte[];
  202. int n;
  203. while ((n = source.Read(bytes, , bytes.Length)) != )
  204. {
  205. output.Write(bytes, , n);
  206. }
  207. }
  208. }
  209. }
  210.  
  211. #endregion
  212.  
  213. [Serializable]
  214. class SerializeFileInfo
  215. {
  216. public SerializeFileInfo(string name, byte[] buffer,string flag,string dirname)
  217. {
  218. fileName = name;
  219. fileBuffer = buffer;
  220. fileflag = flag;
  221. filedirnane = dirname;
  222. }
  223. string fileflag;
  224. string filedirnane;
  225. string fileName;
  226.  
  227. public string Filedirnane
  228. {
  229. get
  230. {
  231. return filedirnane;
  232. }
  233. }
  234. public string Fileflag
  235. {
  236. get
  237. {
  238. return fileflag;
  239. }
  240. }
  241.  
  242. public string FileName
  243. {
  244. get
  245. {
  246. return fileName;
  247. }
  248. }
  249. byte[] fileBuffer;
  250. public byte[] FileBuffer
  251. {
  252. get
  253. {
  254. return fileBuffer;
  255. }
  256. }
  257. }
  258. }
  259. }
  1. CommonBaseInfo.Zip.CompressFolderP(@"c:\debug", @"c:\debug.zip");
  2. CommonBaseInfo.Zip.DeCompressFolder(@"c:\debug.zip", @"c:\debug\");

c# 压缩文件的更多相关文章

  1. 【VC++技术杂谈008】使用zlib解压zip压缩文件

    最近因为项目的需要,要对zip压缩文件进行批量解压.在网上查阅了相关的资料后,最终使用zlib开源库实现了该功能.本文将对zlib开源库进行简单介绍,并给出一个使用zlib开源库对zip压缩文件进行解 ...

  2. C#基础-压缩文件及故障排除

    C#压缩文件可以使用第三方dll库:ICSharpCode.SharpZipLib.dll: 以下代码能实现文件夹与多个文件的同时压缩.(例:把三个文件夹和五个文件一起压缩成一个zip) 直接上代码, ...

  3. 破解压缩文件密码rarcrack

    破解压缩文件密码rarcrack   常见的压缩文件格式有ZIP.RAR和7z.这三种格式都支持使用密码进行加密压缩.前面讲过破解ZIP压缩文件,可以使用fcrackzip.对于RAR和7z格式,可以 ...

  4. 文件打包,下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文件

    总结:                                                          使用PHP下载文件的操作需要给出四个header(),可以参考我的另一篇博文: ...

  5. java ZipOutputStream压缩文件,ZipInputStream解压缩

    java中实现zip的压缩与解压缩.java自带的 能实现的功能比较有限. 本程序功能:实现简单的压缩和解压缩,压缩文件夹下的所有文件(文件过滤的话需要对File进一步细节处理). 对中文的支持需要使 ...

  6. C# 压缩文件与字节互转

    public class ZipBin { public byte[] bytes; //C#读取压缩文件(将压缩文件转换为二进制 public void GetZipToByte(string in ...

  7. Linux如何复制,打包,压缩文件

    (1)复制文件 cp -r  要copy的文件/("/"指的是包括里面的内容)   newfile_name(要命名的文件名) eg:cp -r webapps_zero/   f ...

  8. java生成压缩文件

    在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载.所以自己写了一个压缩文件的工具类.该工具类支持单个文件和文件夹压缩.放代码: import java.io.BufferedOutput ...

  9. 7z压缩文件时排除指定的文件

    分享一个7z压缩文件时排除指定文件类型的命令行,感觉很有用: 7z a -t7z d:\updateCRM.7z d:\updateCRM\*.* -r -x!*.log -x!*bak a:创建压缩 ...

  10. [Java 基础] 使用java.util.zip包压缩和解压缩文件

    reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...

随机推荐

  1. SQl server master

    取一段连续时间,SQl server 2008可用,其他版本暂时没测试.           ),                                      ), )), )      ...

  2. vb.net下载代码

    '后台 Partial Public Class Download2 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender ...

  3. CAST 类型转换应用

    1: select 2: ID,SystemID,Department, 3: case Number when 0 then '若干' else CAST(Number as varchar)+'人 ...

  4. openssl,db,mysql,sasl编译安装

    yum -y install nfs-utils nfs4-acl-tools nfs-utils-libyum -y install gcc gcc* libtool libtools-ltdl l ...

  5. MyBatis框架——mybatis插入数据返回主键(mysql、oracle)

    向数据库中插入数据时,大多数情况都会使用自增列或者UUID做为主键.主键的值都是插入之前无法知道的,但很多情况下我们在插入数据后需要使用刚刚插入数据的主键,比如向两张关联表A.B中插入数据(A的主键是 ...

  6. StarUML建模软件

    这星期本人进行了UML建模语言的初步学习,简单地将上学期所建立的数据库模型在该软件中实现了出来.

  7. Android中px和dip的区别

    在Android手机的诞生之初,由于Android系统是开源的,一开始便有众多的OEM厂商对Android手机进行深度定制,于是乎Android手机的皮肤和屏幕大小都变得百花齐放,这可苦逼了我们这群开 ...

  8. spring mvc ajax 400解决

    The request sent by the client was syntactically incorrect. ajax发起请求时报400错误.请求代码如下: var reportId=($( ...

  9. MySQL的pt-query-digest的下载与使用

    对于脚本文件,是可以执行的,我们不用安装.所以,但是这个脚本文件没有执行的权限,所以,我们首先赋予这个脚本文件的可执行的权限. 再次查看文件的信息后. 已经有了执行的权限了. 运行脚本的时候,可要注意 ...

  10. Qt5.3 打印示例时出现错误

    说明:今天我在用Qt5.3写打印文档的时候,编译出错了,出错代码为: C:\Users\joe\Desktop\5-9\myPrint\mainwindow.cpp:35: error: undefi ...