ZipUtility.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using ICSharpCode.SharpZipLib.Checksum;
  7. using ICSharpCode.SharpZipLib.Zip;
  8. // ReSharper disable All
  9. namespace Team.Utility
  10. {
  11. public class ZipUtility
  12. {
  13. /// <summary>
  14. /// ZIP:压缩单个文件
  15. /// add yuangang by 2016-06-13
  16. /// </summary>
  17. /// <param name="fileToZip">需要压缩的文件(绝对路径)</param>
  18. /// <param name="zipPath">压缩后的文件路径(绝对路径)</param>
  19. /// <param name="zippedFileName">压缩后的文件名称(文件名,默认 同源文件同名)</param>
  20. /// <param name="compressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param>
  21. /// <param name="blockSize">缓存大小(每次写入文件大小,默认 2048)</param>
  22. /// <param name="isEncrypt">是否加密(默认 加密)</param>
  23. public static void Zip(string fileToZip, string zipPath, string zippedFileName = "",
  24. int compressionLevel = 5, int blockSize = 2048, bool isEncrypt = true)
  25. {
  26. //如果文件没有找到,则报错
  27. if (!File.Exists(fileToZip))
  28. {
  29. throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
  30. }
  31. //文件名称(默认同源文件名称相同)
  32. var zipFileName = string.IsNullOrEmpty(zippedFileName)
  33. ? zipPath + "\\" +
  34. new FileInfo(fileToZip).Name.Substring(0, new FileInfo(fileToZip).Name.LastIndexOf('.')) + ".zip"
  35. : zipPath + "\\" + zippedFileName + ".zip";
  36. using (var zipFile = File.Create(zipFileName))
  37. {
  38. using (var zipStream = new ZipOutputStream(zipFile))
  39. {
  40. using (var streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
  41. {
  42. var fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  43. var zipEntry = new ZipEntry(fileName);
  44. if (isEncrypt)
  45. {
  46. //压缩文件加密
  47. zipStream.Password = "123";
  48. }
  49. zipStream.PutNextEntry(zipEntry);
  50. //设置压缩级别
  51. zipStream.SetLevel(compressionLevel);
  52. //缓存大小
  53. var buffer = new byte[blockSize];
  54. int sizeRead;
  55. do
  56. {
  57. sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
  58. zipStream.Write(buffer, 0, sizeRead);
  59. } while (sizeRead > 0);
  60. streamToZip.Close();
  61. }
  62. zipStream.Finish();
  63. zipStream.Close();
  64. }
  65. zipFile.Close();
  66. }
  67. }
  68. /// <summary>
  69. /// ZIP:压缩文件夹
  70. ///
  71. /// </summary>
  72. /// <param name="directoryToZip">需要压缩的文件夹(绝对路径)</param>
  73. /// <param name="zipedPath">压缩后的文件路径(绝对路径)</param>
  74. /// <param name="zipedFileName">压缩后的文件名称(文件名,默认 同源文件夹同名)</param>
  75. /// <param name="isEncrypt">是否加密(默认 加密)</param>
  76. public static void ZipDirectory(string directoryToZip, string zipedPath, string zipedFileName = "",
  77. bool isEncrypt = true)
  78. {
  79. //如果目录不存在,则报错
  80. if (!Directory.Exists(directoryToZip))
  81. {
  82. throw new FileNotFoundException("指定的目录: " + directoryToZip + " 不存在!");
  83. }
  84. //文件名称(默认同源文件名称相同)
  85. var zipFileName = string.IsNullOrEmpty(zipedFileName)
  86. ? zipedPath + "\\" + new DirectoryInfo(directoryToZip).Name + ".zip"
  87. : zipedPath + "\\" + zipedFileName + ".zip";
  88. using (var zipFile = File.Create(zipFileName))
  89. {
  90. using (var s = new ZipOutputStream(zipFile))
  91. {
  92. if (isEncrypt)
  93. {
  94. //压缩文件加密
  95. s.Password = "123";
  96. }
  97. ZipSetp(directoryToZip, s, "");
  98. }
  99. }
  100. }
  101. /// <summary>
  102. /// ZIP:压缩文件夹
  103. /// </summary>
  104. /// <param name="directoryToZip">需要压缩的文件夹(绝对路径)</param>
  105. /// <param name="zipedPath">压缩后的文件路径(绝对路径)</param>
  106. /// <param name="zipedFileName">压缩后的文件名称(文件名,默认 同源文件夹同名)</param>
  107. /// <param name="isEncrypt">是否加密(默认 加密)</param>
  108. public static async Task ZipDirectoryAsync(string directoryToZip, string zipedPath, string zipedFileName = "",
  109. bool isEncrypt = true)
  110. {
  111. //如果目录不存在,则报错
  112. if (!Directory.Exists(directoryToZip))
  113. {
  114. throw new FileNotFoundException("指定的目录: " + directoryToZip + " 不存在!");
  115. }
  116. //文件名称(默认同源文件名称相同)
  117. var zipFileName = string.IsNullOrEmpty(zipedFileName)
  118. ? zipedPath + "\\" + new DirectoryInfo(directoryToZip).Name + ".zip"
  119. : zipedPath + "\\" + zipedFileName + ".zip";
  120. using var zipFile = File.Create(zipFileName);
  121. using var s = new ZipOutputStream(zipFile);
  122. if (isEncrypt)
  123. {
  124. //压缩文件加密
  125. s.Password = "123";
  126. }
  127. await ZipSetpAsync(directoryToZip, s, "");
  128. }
  129. /// <summary>
  130. /// 压缩多层目录
  131. /// </summary>
  132. /// <param name="strDirectory">The directory.</param>
  133. /// <param name="zipedFile">The ziped file.</param>
  134. public static void ZipFileDirectory(string strDirectory, string zipedFile)
  135. {
  136. using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))
  137. {
  138. using (ZipOutputStream s = new ZipOutputStream(ZipFile))
  139. {
  140. ZipSetp(strDirectory, s, "");
  141. }
  142. }
  143. }
  144. public static void ZipFiles(List<string> filesPath,string zipedPath,string zipedFileName = "",
  145. bool isEncrypt = true)
  146. {
  147. //如果目录不存在,则报错
  148. foreach (var filePath in filesPath)
  149. {
  150. throw new FileNotFoundException("指定的目录: " + filePath + " 不存在!");
  151. }
  152. //文件名称(默认同源文件名称相同)
  153. var zipFileName = string.IsNullOrEmpty(zipedFileName)
  154. ? zipedPath + "\\" + new DirectoryInfo(filesPath.First()).Name + ".zip"
  155. : zipedPath + "\\" + zipedFileName + ".zip";
  156. using (var zipFile = File.Create(zipFileName))
  157. {
  158. using (var s = new ZipOutputStream(zipFile))
  159. {
  160. if (isEncrypt)
  161. {
  162. //压缩文件加密
  163. s.Password = "123";
  164. }
  165. ZipSetp(filesPath.First(), s, "");
  166. }
  167. }
  168. }
  169. public static async Task ZipFilesAsync(List<string> filesPathes, string zipedPath, string zipedFileName = "",
  170. int compressionLevel = 5, int blockSize = 2048, bool isEncrypt = true)
  171. {
  172. foreach (var filesPath in filesPathes)
  173. {
  174. //如果文件没有找到,则报错
  175. if (!File.Exists(filesPath))
  176. {
  177. throw new FileNotFoundException("指定要压缩的文件: " + filesPath + " 不存在!");
  178. }
  179. }
  180. //文件名称(默认同源文件名称相同)
  181. var zipFileName = string.IsNullOrEmpty(zipedFileName)
  182. ? zipedPath + "\\" +
  183. new FileInfo(zipedPath).Name.Substring(0, new FileInfo(zipedPath).Name.LastIndexOf('.')) + ".zip"
  184. : zipedPath + "\\" + zipedFileName + ".zip";
  185. using (var zipFile = File.Create(zipFileName))
  186. {
  187. using (var zipStream = new ZipOutputStream(zipFile))
  188. {
  189. foreach (var filesPath in filesPathes)
  190. {
  191. using (var streamToZip = new FileStream(filesPath, FileMode.Open, FileAccess.Read))
  192. {
  193. var fileName =
  194. filesPath.Substring(filesPath.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  195. var zipEntry = new ZipEntry(fileName);
  196. if (isEncrypt)
  197. {
  198. //压缩文件加密
  199. zipStream.Password = "123";
  200. }
  201. zipStream.PutNextEntry(zipEntry);
  202. //设置压缩级别
  203. zipStream.SetLevel(compressionLevel);
  204. //缓存大小
  205. var buffer = new byte[blockSize];
  206. int sizeRead;
  207. do
  208. {
  209. sizeRead = await streamToZip.ReadAsync(buffer, 0, buffer.Length);
  210. await zipStream.WriteAsync(buffer, 0, sizeRead);
  211. } while (sizeRead > 0);
  212. }
  213. }
  214. }
  215. }
  216. }
  217. /// <summary>
  218. /// 递归遍历目录
  219. /// add yuangang by 2016-06-13
  220. /// </summary>
  221. private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)
  222. {
  223. if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
  224. {
  225. strDirectory += Path.DirectorySeparatorChar;
  226. }
  227. var crc = new Crc32();
  228. var fileNames = Directory.GetFileSystemEntries(strDirectory);
  229. foreach (var file in fileNames) // 遍历所有的文件和目录
  230. {
  231. if (Directory.Exists(file)) // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
  232. {
  233. var pPath = parentPath;
  234. pPath += file.Substring(file.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  235. pPath += "\\";
  236. ZipSetp(file, s, pPath);
  237. }
  238. else // 否则直接压缩文件
  239. {
  240. //打开压缩文件
  241. using (var fs = File.OpenRead(file))
  242. {
  243. var buffer = new byte[fs.Length];
  244. fs.Read(buffer, 0, buffer.Length);
  245. var fileName = parentPath +
  246. file.Substring(file.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  247. var entry = new ZipEntry(fileName);
  248. entry.DateTime = DateTime.Now;
  249. entry.Size = fs.Length;
  250. fs.Close();
  251. crc.Reset();
  252. crc.Update(buffer);
  253. entry.Crc = crc.Value;
  254. s.PutNextEntry(entry);
  255. s.Write(buffer, 0, buffer.Length);
  256. }
  257. }
  258. }
  259. }
  260. private static async Task ZipSetpAsync(string strDirectory, ZipOutputStream s, string parentPath)
  261. {
  262. if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
  263. {
  264. strDirectory += Path.DirectorySeparatorChar;
  265. }
  266. var crc = new Crc32();
  267. var fileNames = Directory.GetFileSystemEntries(strDirectory);
  268. foreach (var file in fileNames) // 遍历所有的文件和目录
  269. {
  270. if (Directory.Exists(file)) // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
  271. {
  272. var pPath = parentPath;
  273. pPath += file.Substring(file.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  274. pPath += "\\";
  275. ZipSetp(file, s, pPath);
  276. }
  277. else // 否则直接压缩文件
  278. {
  279. //打开压缩文件
  280. using var fs = File.OpenRead(file);
  281. var buffer = new byte[fs.Length];
  282. await fs.ReadAsync(buffer, 0, buffer.Length);
  283. var fileName = parentPath +
  284. file.Substring(file.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  285. var entry = new ZipEntry(fileName);
  286. entry.DateTime = DateTime.Now;
  287. entry.Size = fs.Length;
  288. crc.Reset();
  289. crc.Update(buffer);
  290. entry.Crc = crc.Value;
  291. s.PutNextEntry(entry);
  292. await s.WriteAsync(buffer, 0, buffer.Length);
  293. }
  294. }
  295. }
  296. /// <summary>
  297. /// ZIP:解压一个zip文件
  298. /// add yuangang by 2016-06-13
  299. /// </summary>
  300. /// <param name="zipFile">需要解压的Zip文件(绝对路径)</param>
  301. /// <param name="targetDirectory">解压到的目录</param>
  302. /// <param name="password">解压密码</param>
  303. /// <param name="overWrite">是否覆盖已存在的文件</param>
  304. public static void UnZip(string zipFile, string targetDirectory, string password, bool overWrite = true)
  305. {
  306. //如果解压到的目录不存在,则报错
  307. if (!Directory.Exists(targetDirectory))
  308. {
  309. throw new FileNotFoundException("指定的目录: " + targetDirectory + " 不存在!");
  310. }
  311. //目录结尾
  312. if (!targetDirectory.EndsWith("\\")) { targetDirectory = targetDirectory + "\\"; }
  313. using (var zipFiles = new ZipInputStream(File.OpenRead(zipFile)))
  314. {
  315. zipFiles.Password = password;
  316. ZipEntry theEntry;
  317. while ((theEntry = zipFiles.GetNextEntry()) != null)
  318. {
  319. var directoryName = "";
  320. var pathToZip = theEntry.Name;
  321. if (pathToZip != "")
  322. directoryName = Path.GetDirectoryName(pathToZip) + "\\";
  323. var fileName = Path.GetFileName(pathToZip);
  324. Directory.CreateDirectory(targetDirectory + directoryName);
  325. if (fileName == "") continue;
  326. if ((!File.Exists(targetDirectory + directoryName + fileName) || !overWrite) &&
  327. (File.Exists(targetDirectory + directoryName + fileName))) continue;
  328. using (var streamWriter = File.Create(targetDirectory + directoryName + fileName))
  329. {
  330. var data = new byte[2048];
  331. while (true)
  332. {
  333. var size = zipFiles.Read(data, 0, data.Length);
  334. if (size > 0)
  335. streamWriter.Write(data, 0, size);
  336. else
  337. break;
  338. }
  339. streamWriter.Close();
  340. }
  341. }
  342. zipFiles.Close();
  343. }
  344. }
  345. }
  346. }