ZipHelper.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. 
  2. using System;
  3. using System.IO;
  4. using ICSharpCode.SharpZipLib.Zip;
  5. using ICSharpCode.SharpZipLib.Core;
  6. using IES.ExamServer.DI.SignalRHost;
  7. using IES.ExamServer.Models;
  8. using Microsoft.AspNetCore.SignalR;
  9. using Microsoft.Extensions.Caching.Memory;
  10. using IES.ExamServer.Helper;
  11. namespace IES.ExamServer.Helpers
  12. {
  13. public static class ZipHelper
  14. {
  15. /*
  16. static void Main(string[] args)
  17. {
  18. string sourceDirectory = "path/to/your/source/directory";
  19. string zipFilePath = "protected.zip";
  20. string extractPath = "path/to/extract/folder";
  21. string password = "yourpassword";
  22. // 创建带密码的 ZIP 文件
  23. bool zipResult = ZipHelper.CreatePasswordProtectedZip(sourceDirectory, zipFilePath, password);
  24. if (zipResult)
  25. {
  26. Console.WriteLine("压缩成功!");
  27. }
  28. else
  29. {
  30. Console.WriteLine("压缩失败!");
  31. }
  32. // 解压带密码的 ZIP 文件
  33. bool extractResult = ZipHelper.ExtractPasswordProtectedZip(zipFilePath, extractPath, password);
  34. if (extractResult)
  35. {
  36. Console.WriteLine("解压成功!");
  37. }
  38. else
  39. {
  40. Console.WriteLine("解压失败!");
  41. }
  42. }
  43. */
  44. /// <summary>
  45. /// 创建带密码的 ZIP 文件
  46. /// </summary>
  47. /// <param name="sourceDirectory">要压缩的目录路径</param>
  48. /// <param name="zipFilePath">生成的 ZIP 文件路径</param>
  49. /// <param name="password">ZIP 文件密码</param>
  50. /// <returns>是否成功</returns>
  51. public static (bool res, string msg) CreatePasswordProtectedZip(string sourceDirectory, string zipFilePath, string password)
  52. {
  53. if (!Directory.Exists(sourceDirectory))
  54. {
  55. // Console.WriteLine("源目录不存在。");
  56. return (false, "源目录不存在。");
  57. }
  58. try
  59. {
  60. using (FileStream fsOut = File.Create(zipFilePath))
  61. using (ZipOutputStream zipStream = new ZipOutputStream(fsOut))
  62. {
  63. zipStream.SetLevel(0); // 设置压缩级别 (0-9)
  64. zipStream.Password = password; // 设置密码
  65. CompressFolder(sourceDirectory, zipStream, "");
  66. }
  67. //Console.WriteLine($"ZIP 文件已成功创建:{zipFilePath}");
  68. return (true, $"ZIP 文件已成功创建") ;
  69. }
  70. catch (Exception ex)
  71. {
  72. // Console.WriteLine($"创建 ZIP 文件时发生错误:{ex.Message}");
  73. return (false, $"创建 ZIP 文件时发生错误!");
  74. }
  75. }
  76. /// <summary>
  77. /// 解压带密码的 ZIP 文件
  78. /// </summary>
  79. /// <param name="zipFilePath">ZIP 文件路径</param>
  80. /// <param name="extractPath">解压目标目录</param>
  81. /// <param name="password">ZIP 文件密码</param>
  82. /// <returns>是否成功</returns>
  83. public static async Task<(bool res, string msg)> ExtractPasswordProtectedZip(string zipFilePath, string extractPath, string password,
  84. IHubContext<SignalRExamServerHub> _signalRExamServerHub,IMemoryCache _memoryCache,ILogger _logger,string deviceId, EvaluationClient evaluationClient)
  85. {
  86. if (!File.Exists(zipFilePath))
  87. {
  88. return (false, "ZIP 文件不存在。");
  89. }
  90. try
  91. {
  92. using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
  93. {
  94. zipInputStream.Password = password; // 设置解压密码
  95. ZipEntry entry;
  96. long blobCount = evaluationClient.blobCount + 3;
  97. long currCount = 0 ;
  98. while ((entry = zipInputStream.GetNextEntry()) != null)
  99. {
  100. currCount++;
  101. string entryFileName = entry.Name;
  102. string fullPath = Path.Combine(extractPath, entryFileName);
  103. await _signalRExamServerHub.SendMessage(_memoryCache, _logger, deviceId, Constant._Message_grant_type_download_file,
  104. new MessageContent { dataId = evaluationClient.id, dataName = evaluationClient.name, messageType = Constant._Message_type_message, status = Constant._Message_status_success, content = $"[进度:{currCount}/[{blobCount}]],正在解压:{entryFileName}" });
  105. // 创建目录(如果条目是目录)
  106. string? directoryName = Path.GetDirectoryName(fullPath);
  107. if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
  108. {
  109. Directory.CreateDirectory(directoryName);
  110. }
  111. // 如果是文件,则解压文件
  112. if (!entry.IsDirectory)
  113. {
  114. using (FileStream streamWriter = File.Create(fullPath))
  115. {
  116. byte[] buffer = new byte[4096];
  117. int bytesRead;
  118. while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
  119. {
  120. streamWriter.Write(buffer, 0, bytesRead);
  121. }
  122. }
  123. }
  124. }
  125. }
  126. return (true, $"ZIP 文件已成功解压到:{extractPath}");
  127. }
  128. catch (Exception ex)
  129. {
  130. return (false, $"解压 ZIP 文件时发生错误:{ex.Message}");
  131. }
  132. }
  133. /// <summary>
  134. /// 递归压缩文件夹
  135. /// </summary>
  136. private static void CompressFolder(string path, ZipOutputStream zipStream, string folderName)
  137. {
  138. foreach (string file in Directory.GetFiles(path))
  139. {
  140. string fileName = Path.GetFileName(file);
  141. string relativePath = Path.Combine(folderName, fileName);
  142. ZipEntry entry = new ZipEntry(relativePath);
  143. entry.DateTime = DateTime.Now;
  144. zipStream.PutNextEntry(entry);
  145. using (FileStream fs = File.OpenRead(file))
  146. {
  147. byte[] buffer = new byte[4096];
  148. int bytesRead;
  149. while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
  150. {
  151. zipStream.Write(buffer, 0, bytesRead);
  152. }
  153. }
  154. zipStream.CloseEntry();
  155. }
  156. // 递归处理子目录
  157. foreach (string folder in Directory.GetDirectories(path))
  158. {
  159. string folderNameOnly = Path.GetFileName(folder);
  160. string newFolderName = Path.Combine(folderName, folderNameOnly);
  161. CompressFolder(folder, zipStream, newFolderName);
  162. }
  163. }
  164. }
  165. }