ZipUtility.cs 10 KB

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