ZipHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. using ICSharpCode.SharpZipLib.Zip;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace XYY.Common.Standard
  9. {
  10. public static class ZipHelper
  11. {
  12. /// <summary>
  13. /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略)
  14. /// </summary>
  15. /// <param name="dirPath">被压缩的文件夹夹路径</param>
  16. /// <param name="zipFilePath">生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip</param>
  17. /// <param name="err">出错信息</param>
  18. /// <returns>是否压缩成功</returns>
  19. public static void ZipPath(string dirPath, string zipFilePath)
  20. {
  21. if (dirPath == string.Empty)
  22. {
  23. throw new Exception("要压缩的文件夹不能为空!");
  24. }
  25. if (!Directory.Exists(dirPath))
  26. {
  27. throw new Exception("要压缩的文件夹不存在!");
  28. }
  29. //压缩文件名为空时使用文件夹名+.zip
  30. if (zipFilePath == string.Empty)
  31. {
  32. if (dirPath.EndsWith("\\"))
  33. {
  34. dirPath = dirPath.Substring(0, dirPath.Length - 1);
  35. }
  36. zipFilePath = dirPath + ".zip";
  37. }
  38. try
  39. {
  40. string[] filenames = Directory.GetFiles(dirPath);
  41. using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
  42. {
  43. s.SetLevel(9);
  44. byte[] buffer = new byte[4096];
  45. foreach (string file in filenames)
  46. {
  47. ZipEntry entry = new ZipEntry(Path.GetFileName(file));
  48. entry.DateTime = DateTime.Now;
  49. s.PutNextEntry(entry);
  50. using (FileStream fs = File.OpenRead(file))
  51. {
  52. int sourceBytes;
  53. do
  54. {
  55. sourceBytes = fs.Read(buffer, 0, buffer.Length);
  56. s.Write(buffer, 0, sourceBytes);
  57. } while (sourceBytes > 0);
  58. }
  59. }
  60. s.Finish();
  61. s.Close();
  62. }
  63. }
  64. catch
  65. {
  66. throw;
  67. }
  68. }
  69. /// <summary>
  70. /// 重载一个方法
  71. /// </summary>
  72. /// <param name="dirPath"></param>
  73. /// <param name="zipFilePath"></param>
  74. /// <param name="filtration">过滤 指定后缀数据</param>
  75. /// <param name="maxSize">限制大小 byte 1m=1024*1024 1kb=1024b 根据单个文件大小,进行模糊设置</param>
  76. /// <exception cref="Exception"></exception>
  77. public static List<string> ZipPath(string dirPath, string zipFilePath, string filtration, int maxSize)
  78. {
  79. if (dirPath == string.Empty)
  80. {
  81. throw new Exception("要压缩的文件夹不能为空!");
  82. }
  83. if (!Directory.Exists(dirPath))
  84. {
  85. throw new Exception("要压缩的文件夹不存在!");
  86. }
  87. //压缩文件名为空时使用文件夹名+.zip
  88. if (zipFilePath == string.Empty)
  89. {
  90. if (dirPath.EndsWith("\\"))
  91. {
  92. dirPath = dirPath.Substring(0, dirPath.Length - 1);
  93. }
  94. zipFilePath = dirPath + ".zip";
  95. }
  96. List<string> zips = new List<string>();
  97. try
  98. {
  99. List<string> filenames = Directory.GetFiles(dirPath).ToList();
  100. int allFileNames = filenames.Count;
  101. List<string> tempFile = new List<string>();
  102. int count = 0;
  103. do
  104. {
  105. if (tempFile.Count > 0) { filenames.RemoveAll(x => tempFile.Contains(x)); tempFile.Clear(); }
  106. count++;
  107. string rootPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(@"\") + 1);
  108. string filePath = zipFilePath.Substring(zipFilePath.LastIndexOf(@"\") + 1, zipFilePath.Length - zipFilePath.LastIndexOf(@"\") - 1);
  109. zipFilePath = rootPath + filePath.Split(".")[0].Split("-")[0] + $"-{count}" + ".zip";
  110. zips.Add(zipFilePath);
  111. using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
  112. {
  113. s.SetLevel(9);
  114. byte[] buffer = new byte[4096];
  115. int totalLength = 0;
  116. foreach (string file in filenames)
  117. {
  118. if (!string.IsNullOrEmpty(filtration)) { if (file.Contains(filtration)) { continue; } } //过滤文件
  119. ZipEntry entry = new ZipEntry(Path.GetFileName(file));
  120. entry.DateTime = DateTime.Now;
  121. s.PutNextEntry(entry);
  122. using (FileStream fs = File.OpenRead(file))
  123. {
  124. int sourceBytes;
  125. do
  126. {
  127. sourceBytes = fs.Read(buffer, 0, buffer.Length);
  128. totalLength += sourceBytes;
  129. if (totalLength > maxSize) { break; }
  130. s.Write(buffer, 0, sourceBytes);
  131. } while (sourceBytes > 0);
  132. }
  133. //跳出循环
  134. if (totalLength > maxSize) { break; }
  135. allFileNames--;
  136. tempFile.Add(file);
  137. }
  138. s.Finish();
  139. s.Close();
  140. }
  141. } while (allFileNames > 0);
  142. return zips;
  143. }
  144. catch
  145. {
  146. throw;
  147. }
  148. }
  149. /// <summary>
  150. /// 功能:解压zip格式的文件。
  151. /// </summary>
  152. /// <param name="zipFilePath">压缩文件路径</param>
  153. /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
  154. /// <param name="err">出错信息</param>
  155. /// <returns>解压是否成功</returns>
  156. public static void UnZipPath(string zipFilePath, string unZipDir)
  157. {
  158. if (zipFilePath == string.Empty)
  159. {
  160. throw new Exception("压缩文件不能为空!");
  161. }
  162. if (!File.Exists(zipFilePath))
  163. {
  164. throw new Exception("压缩文件不存在!");
  165. }
  166. //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
  167. if (unZipDir == string.Empty)
  168. unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
  169. if (!unZipDir.EndsWith("\\"))
  170. unZipDir += "\\";
  171. if (!Directory.Exists(unZipDir))
  172. Directory.CreateDirectory(unZipDir);
  173. try
  174. {
  175. using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
  176. {
  177. ZipEntry theEntry;
  178. while ((theEntry = s.GetNextEntry()) != null)
  179. {
  180. string directoryName = Path.GetDirectoryName(theEntry.Name);
  181. string fileName = Path.GetFileName(theEntry.Name);
  182. if (directoryName.Length > 0)
  183. {
  184. Directory.CreateDirectory(unZipDir + directoryName);
  185. }
  186. if (!directoryName.EndsWith("\\"))
  187. directoryName += "\\";
  188. if (fileName != string.Empty)
  189. {
  190. using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
  191. {
  192. int size = 2048;
  193. byte[] data = new byte[2048];
  194. while (true)
  195. {
  196. size = s.Read(data, 0, data.Length);
  197. if (size > 0)
  198. {
  199. streamWriter.Write(data, 0, size);
  200. }
  201. else
  202. {
  203. break;
  204. }
  205. }
  206. }
  207. }
  208. }//while
  209. }
  210. }
  211. catch
  212. {
  213. throw;
  214. }
  215. }
  216. public static Stream ZipStream(IEnumerable<ZipItem> streams)
  217. {
  218. MemoryStream ms = new MemoryStream();
  219. ZipOutputStream s = new ZipOutputStream(ms);
  220. s.SetLevel(9);
  221. byte[] buffer = new byte[4096];
  222. foreach (var item in streams)
  223. {
  224. ZipEntry entry = new ZipEntry(item.FileName);
  225. entry.DateTime = DateTime.Now;
  226. s.PutNextEntry(entry);
  227. int sourceBytes;
  228. do
  229. {
  230. sourceBytes = item.Stream.Read(buffer, 0, buffer.Length);
  231. s.Write(buffer, 0, sourceBytes);
  232. } while (sourceBytes > 0);
  233. }
  234. s.Finish();
  235. ms.Position = 0;
  236. return ms;
  237. }
  238. //public static Stream WriteZip(params ZipItem[] streams)
  239. //{
  240. // MemoryStream ms = new MemoryStream();
  241. // ZipOutputStream zipOut = null; // 定义压缩输出流
  242. // zipOut = new ZipOutputStream(ms); // 实例化压缩输出流对象,并指定压缩文件的输出路径
  243. // for (int i = 0; i < streams.Length; i++)
  244. // {
  245. // zipOut.PutNextEntry(new ZipEntry(streams[i].FileName)); // 创建ZipEntry 每一个被压缩的文件都用ZipEntry表示,需要为每一个压缩后的文件设置名称
  246. // zipOut.SetComment("这里是注释"); // 设置注释
  247. // Stream fs = streams[i].Stream;//file.OpenRead();//定义输出流
  248. // long dataLengthToRead = fs.Length; ////获取输出流总大小
  249. // while (dataLengthToRead > 0)
  250. // { // 读取内容
  251. // byte[] buffer = new byte[524288];
  252. // int lengthRead = fs.Read(buffer, 0, buffer.Length);//读取的大小
  253. // zipOut.Write(buffer, 0, lengthRead); // 压缩输出内容
  254. // dataLengthToRead = dataLengthToRead - lengthRead;
  255. // }
  256. // fs.Close(); // 关闭输入流
  257. // }
  258. // zipOut.Finish(); //完成压缩流
  259. // //zipOut.Close(); // 关闭压缩输出流
  260. // ms.Position = 0;
  261. // return ms;
  262. //}
  263. }
  264. public class ZipItem
  265. {
  266. public ZipItem(string fileName, Stream stream)
  267. {
  268. this.FileName = fileName;
  269. this.Stream = stream;
  270. }
  271. public string FileName
  272. {
  273. get;
  274. set;
  275. }
  276. public Stream Stream
  277. {
  278. get;
  279. set;
  280. }
  281. }
  282. }