平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ZipUtils.cs 17 KiB

4 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. 
  2. //
  3. namespace SafeCampus.Core.Utils;
  4. public class ZipUtils
  5. {
  6. /// <summary>
  7. /// 压缩单个文件
  8. /// </summary>
  9. /// <param name="fileToZip">要压缩的文件</param>
  10. /// <param name="zipedFile">压缩后的文件</param>
  11. /// <param name="compressionLevel">压缩等级</param>
  12. /// <param name="blockSize">每次写入大小</param>
  13. public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel,
  14. int blockSize)
  15. {
  16. //如果文件没有找到,则报错
  17. if (!File.Exists(fileToZip))
  18. {
  19. throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
  20. }
  21. using (var zipFile = File.Create(zipedFile))
  22. {
  23. using (var zipStream = new ZipOutputStream(zipFile))
  24. {
  25. using (var streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
  26. {
  27. var fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  28. var zipEntry = new ZipEntry(fileName);
  29. zipStream.PutNextEntry(zipEntry);
  30. zipStream.SetLevel(compressionLevel);
  31. var buffer = new byte[blockSize];
  32. try
  33. {
  34. var sizeRead = 0;
  35. do
  36. {
  37. sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
  38. zipStream.Write(buffer, 0, sizeRead);
  39. } while (sizeRead > 0);
  40. }
  41. catch (Exception ex)
  42. {
  43. throw ex;
  44. }
  45. streamToZip.Close();
  46. }
  47. zipStream.Finish();
  48. zipStream.Close();
  49. }
  50. zipFile.Close();
  51. }
  52. }
  53. /// <summary>
  54. /// 压缩单个文件
  55. /// </summary>
  56. /// <param name="fileToZip">要进行压缩的文件名</param>
  57. /// <param name="zipedFile">压缩后生成的压缩文件名</param>
  58. public static void ZipFile(string fileToZip, string zipedFile)
  59. {
  60. //如果文件没有找到,则报错
  61. if (!File.Exists(fileToZip))
  62. {
  63. throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
  64. }
  65. using (var fs = File.OpenRead(fileToZip))
  66. {
  67. var buffer = new byte[fs.Length];
  68. fs.Read(buffer, 0, buffer.Length);
  69. fs.Close();
  70. using (var zipFile = File.Create(zipedFile))
  71. {
  72. using (var zipStream = new ZipOutputStream(zipFile))
  73. {
  74. var fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
  75. var zipEntry = new ZipEntry(fileName);
  76. zipStream.PutNextEntry(zipEntry);
  77. zipStream.SetLevel(5);
  78. zipStream.Write(buffer, 0, buffer.Length);
  79. zipStream.Finish();
  80. zipStream.Close();
  81. }
  82. }
  83. }
  84. }
  85. /// <summary>
  86. /// 压缩多个文件到指定路径
  87. /// </summary>
  88. /// <param name="sourceFileNames">压缩到哪个路径</param>
  89. /// <param name="zipFileName">压缩文件名称</param>
  90. public static void ZipFile(List<string> sourceFileNames, string zipFileName)
  91. {
  92. //压缩文件打包
  93. using (var s = new ZipOutputStream(File.Create(zipFileName)))
  94. {
  95. s.SetLevel(9);
  96. var buffer = new byte[4096];
  97. foreach (var file in sourceFileNames)
  98. {
  99. if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
  100. {
  101. var pPath = "";
  102. pPath += Path.GetFileName(file);
  103. pPath += "\\";
  104. ZipSetp(file, s, pPath, sourceFileNames);
  105. }
  106. else// 否则直接压缩文件
  107. {
  108. var entry = new ZipEntry(Path.GetFileName(file));
  109. entry.DateTime = DateTime.Now;
  110. s.PutNextEntry(entry);
  111. using (var fs = File.OpenRead(file))
  112. {
  113. int sourceBytes;
  114. do
  115. {
  116. sourceBytes = fs.Read(buffer, 0, buffer.Length);
  117. s.Write(buffer, 0, sourceBytes);
  118. } while (sourceBytes > 0);
  119. }
  120. }
  121. }
  122. s.Finish();
  123. s.Close();
  124. }
  125. }
  126. /// <summary>
  127. /// 压缩多层目录
  128. /// </summary>
  129. /// <param name="strDirectory">待压缩目录</param>
  130. /// <param name="zipedFile">压缩后生成的压缩文件名,绝对路径</param>
  131. public static void ZipFileDirectory(string strDirectory, string zipedFile)
  132. {
  133. using (var zipFile = File.Create(zipedFile))
  134. {
  135. using (var s = new ZipOutputStream(zipFile))
  136. {
  137. s.SetLevel(9);
  138. ZipSetp(strDirectory, s, "");
  139. }
  140. }
  141. }
  142. /// <summary>
  143. /// 压缩多层目录
  144. /// </summary>
  145. /// <param name="strDirectory">待压缩目录</param>
  146. /// <param name="zipedFile">压缩后生成的压缩文件名,绝对路径</param>
  147. /// <param name="files">指定要压缩的文件列表(完全路径)</param>
  148. public static void ZipFileDirectory(string strDirectory, string zipedFile, List<string> files)
  149. {
  150. using (var zipFile = File.Create(zipedFile))
  151. {
  152. using (var s = new ZipOutputStream(zipFile))
  153. {
  154. s.SetLevel(9);
  155. ZipSetp(strDirectory, s, "", files);
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// 递归遍历目录
  161. /// </summary>
  162. /// <param name="strDirectory">需遍历的目录</param>
  163. /// <param name="s">压缩输出流对象</param>
  164. /// <param name="parentPath">The parent path.</param>
  165. /// <param name="files">需要压缩的文件</param>
  166. private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath,
  167. List<string> files = null)
  168. {
  169. if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
  170. {
  171. strDirectory += Path.DirectorySeparatorChar;
  172. }
  173. var filenames = Directory.GetFileSystemEntries(strDirectory);
  174. var buffer = new byte[4096];
  175. foreach (var file in filenames)// 遍历所有的文件和目录
  176. {
  177. if (files != null && !files.Contains(file))
  178. {
  179. continue;
  180. }
  181. if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
  182. {
  183. var pPath = parentPath;
  184. pPath += Path.GetFileName(file);
  185. pPath += "\\";
  186. ZipSetp(file, s, pPath, files);
  187. }
  188. else// 否则直接压缩文件
  189. {
  190. //打开压缩文件
  191. var fileName = parentPath + Path.GetFileName(file);
  192. var entry = new ZipEntry(fileName);
  193. entry.DateTime = DateTime.Now;
  194. s.PutNextEntry(entry);
  195. using (var fs = File.OpenRead(file))
  196. {
  197. int sourceBytes;
  198. do
  199. {
  200. sourceBytes = fs.Read(buffer, 0, buffer.Length);
  201. s.Write(buffer, 0, sourceBytes);
  202. } while (sourceBytes > 0);
  203. }
  204. }
  205. }
  206. }
  207. /// <summary>
  208. /// 解压缩一个 zip 文件。
  209. /// </summary>
  210. /// <param name="zipedFile">压缩文件</param>
  211. /// <param name="strDirectory">解压目录</param>
  212. /// <param name="password">zip 文件的密码。</param>
  213. /// <param name="overWrite">是否覆盖已存在的文件。</param>
  214. public static void UnZip(string zipedFile, string strDirectory, bool overWrite,
  215. string password)
  216. {
  217. if (strDirectory == "")
  218. strDirectory = Directory.GetCurrentDirectory();
  219. if (!strDirectory.EndsWith("\\"))
  220. strDirectory = strDirectory + "\\";
  221. using (var s = new ZipInputStream(File.OpenRead(zipedFile)))
  222. {
  223. if (password != null)
  224. {
  225. s.Password = password;
  226. }
  227. ZipEntry theEntry;
  228. while ((theEntry = s.GetNextEntry()) != null)
  229. {
  230. var directoryName = "";
  231. var pathToZip = "";
  232. pathToZip = theEntry.Name;
  233. if (pathToZip != "")
  234. directoryName = Path.GetDirectoryName(pathToZip) + "\\";
  235. var fileName = Path.GetFileName(pathToZip);
  236. Directory.CreateDirectory(strDirectory + directoryName);
  237. if (fileName != "")
  238. {
  239. if (File.Exists(strDirectory + directoryName + fileName) && overWrite || !File.Exists(strDirectory + directoryName + fileName))
  240. {
  241. using (var streamWriter = File.Create(strDirectory + directoryName + fileName))
  242. {
  243. var size = 2048;
  244. var data = new byte[2048];
  245. while (true)
  246. {
  247. size = s.Read(data, 0, data.Length);
  248. if (size > 0)
  249. streamWriter.Write(data, 0, size);
  250. else
  251. break;
  252. }
  253. streamWriter.Close();
  254. }
  255. }
  256. }
  257. }
  258. s.Close();
  259. }
  260. }
  261. /// <summary>
  262. /// 解压缩一个 zip 文件。
  263. /// </summary>
  264. /// <param name="zipedFile">压缩文件</param>
  265. /// <param name="strDirectory">解压目录</param>
  266. /// <param name="overWrite">是否覆盖已存在的文件。</param>
  267. public static void UnZip(string zipedFile, string strDirectory, bool overWrite)
  268. {
  269. UnZip(zipedFile, strDirectory, overWrite, null);
  270. }
  271. /// <summary>
  272. /// 解压缩一个 zip 文件。
  273. /// 覆盖已存在的文件。
  274. /// </summary>
  275. /// <param name="zipedFile">压缩文件</param>
  276. /// <param name="strDirectory">解压目录</param>
  277. public static void UnZip(string zipedFile, string strDirectory)
  278. {
  279. UnZip(zipedFile, strDirectory, true);
  280. }
  281. /// <summary>
  282. /// 获取压缩文件中指定类型的文件
  283. /// </summary>
  284. /// <param name="zipedFile">压缩文件</param>
  285. /// <param name="fileExtension">文件类型(.txt|.exe)</param>
  286. /// <returns>文件名称列表(包含子目录)</returns>
  287. public static List<string> GetFiles(string zipedFile, List<string> fileExtension)
  288. {
  289. var files = new List<string>();
  290. if (!File.Exists(zipedFile))
  291. {
  292. //return files;
  293. throw new FileNotFoundException(zipedFile);
  294. }
  295. using (var s = new ZipInputStream(File.OpenRead(zipedFile)))
  296. {
  297. ZipEntry theEntry;
  298. while ((theEntry = s.GetNextEntry()) != null)
  299. {
  300. if (theEntry.IsFile)
  301. {
  302. //Console.WriteLine("Name : {0}", theEntry.Name);
  303. if (fileExtension != null)
  304. {
  305. if (fileExtension.Contains(Path.GetExtension(theEntry.Name)))
  306. {
  307. files.Add(theEntry.Name);
  308. }
  309. }
  310. else
  311. {
  312. files.Add(theEntry.Name);
  313. }
  314. }
  315. }
  316. s.Close();
  317. }
  318. return files;
  319. }
  320. /// <summary>
  321. /// 获取压缩文件中的所有文件
  322. /// </summary>
  323. /// <param name="zipedFile">压缩文件</param>
  324. /// <returns>文件名称列表(包含子目录)</returns>
  325. public static List<string> GetFiles(string zipedFile)
  326. {
  327. return GetFiles(zipedFile, null);
  328. }
  329. /// <summary>
  330. /// 打包线上线下文件
  331. /// </summary>
  332. /// <param name="zipName">压缩文件名称</param>
  333. /// <param name="fileList">文件列表</param>
  334. /// <param name="error">保存路径</param>
  335. /// <param name="isLocal">是否本地</param>
  336. public static string ZipFiles(string zipName, List<FileItem> fileList, out string error,
  337. bool isLocal = true)
  338. {
  339. error = string.Empty;
  340. var path = string.Format("/ZipFiles/{0}/{1}/{2}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
  341. //文件保存目录
  342. var directory = App.WebHostEnvironment.WebRootPath + path;
  343. var url = App.Configuration["FileHostUrl"].TrimEnd('/') + path + zipName;
  344. var savePath = directory + zipName;
  345. try
  346. {
  347. if (!Directory.Exists(directory))
  348. {
  349. Directory.CreateDirectory(directory);
  350. }
  351. using (var zipStream = new ZipOutputStream(File.Create(savePath)))
  352. {
  353. zipStream.SetLevel(9);//压缩级别0-9
  354. foreach (var item in fileList)
  355. {
  356. byte[] buffer = null;
  357. if (isLocal)
  358. {
  359. var stream = new FileInfo(item.FilePath).OpenRead();
  360. buffer = new byte[stream.Length];
  361. stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
  362. }
  363. else
  364. {
  365. buffer = new WebClient().DownloadData(item.FilePath);//取消
  366. }
  367. var entry = new ZipEntry(item.FileName);
  368. entry.DateTime = DateTime.Now;
  369. entry.Size = buffer.Length;
  370. zipStream.PutNextEntry(entry);
  371. zipStream.Write(buffer, 0, buffer.Length);
  372. }
  373. }
  374. }
  375. catch (Exception ex)
  376. {
  377. error = "文件打包失败:" + ex.Message;
  378. }
  379. return url;
  380. }
  381. /// 压缩文件夹
  382. /// 要打包的文件夹
  383. /// 是否删除原文件夹
  384. public static string CompressDirectory(string dirPath, bool deleteDir)
  385. {
  386. //压缩文件路径
  387. var pCompressPath = dirPath + ".zip";
  388. if (File.Exists(pCompressPath))
  389. File.Delete(pCompressPath);
  390. //创建压缩文件
  391. var pCompressFile = new FileStream(pCompressPath, FileMode.Create);
  392. using (var zipoutputstream = new ZipOutputStream(pCompressFile))
  393. {
  394. var crc = new Crc32();
  395. var fileList = GetAllFies(dirPath);
  396. foreach (var item in fileList)
  397. {
  398. var fs = new FileStream(item.Key, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  399. // FileStream fs = File.OpenRead(item.Key.ToString());
  400. var buffer = new byte[fs.Length];
  401. fs.Read(buffer, 0, buffer.Length);
  402. var entry = new ZipEntry(item.Key.Substring(dirPath.Length));
  403. entry.DateTime = item.Value;
  404. entry.Size = fs.Length;
  405. fs.Close();
  406. crc.Reset();
  407. crc.Update(buffer);
  408. entry.Crc = crc.Value;
  409. zipoutputstream.PutNextEntry(entry);
  410. zipoutputstream.Write(buffer, 0, buffer.Length);
  411. }
  412. }
  413. if (deleteDir)
  414. {
  415. Directory.Delete(dirPath, true);
  416. }
  417. return pCompressPath;
  418. }
  419. ///
  420. /// 获取所有文件
  421. ///
  422. ///
  423. private static Dictionary<string, DateTime> GetAllFies(string dir)
  424. {
  425. var filesList = new Dictionary<string, DateTime>();
  426. var fileDire = new DirectoryInfo(dir);
  427. if (!fileDire.Exists)
  428. {
  429. throw new FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
  430. }
  431. GetAllDirFiles(fileDire, filesList);
  432. GetAllDirsFiles(fileDire.GetDirectories(), filesList);
  433. return filesList;
  434. }
  435. ///
  436. /// 获取一个文件夹下的所有文件夹里的文件
  437. ///
  438. ///
  439. ///
  440. private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<string, DateTime> filesList)
  441. {
  442. foreach (var dir in dirs)
  443. {
  444. foreach (var file in dir.GetFiles("."))
  445. {
  446. filesList.Add(file.FullName, file.LastWriteTime);
  447. }
  448. GetAllDirsFiles(dir.GetDirectories(), filesList);
  449. }
  450. }
  451. ///
  452. /// 获取一个文件夹下的文件
  453. ///
  454. /// 目录名称
  455. /// 文件列表HastTable
  456. private static void GetAllDirFiles(DirectoryInfo dir, Dictionary<string, DateTime> filesList)
  457. {
  458. foreach (var file in dir.GetFiles())
  459. {
  460. filesList.Add(file.FullName, file.LastWriteTime);
  461. }
  462. }
  463. }
  464. /// <summary>
  465. /// 文件对象
  466. /// </summary>
  467. public class FileItem
  468. {
  469. /// <summary>
  470. /// 文件名称
  471. /// </summary>
  472. public string FileName { get; set; }
  473. /// <summary>
  474. /// 文件路径
  475. /// </summary>
  476. public string FilePath { get; set; }
  477. }