Compress.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. using Microsoft.Extensions.Caching.Memory;
  2. using Microsoft.Win32;
  3. using SharpCompress.Archives;
  4. using SharpCompress.Archives.Rar;
  5. using SharpCompress.Archives.Zip;
  6. using SharpCompress.Common;
  7. using SharpCompress.Readers;
  8. using SharpCompress.Writers;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net.Http;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. namespace Masuit.Tools.Files
  18. {
  19. /// <summary>
  20. /// 7z压缩
  21. /// </summary>
  22. public class SevenZipCompressor : ISevenZipCompressor
  23. {
  24. private readonly HttpClient _httpClient;
  25. private static readonly MemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions());
  26. internal static bool EnableCache { get; set; }
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. /// <param name="httpClientFactory"></param>
  31. public SevenZipCompressor(IHttpClientFactory httpClientFactory)
  32. {
  33. _httpClient = httpClientFactory.CreateClient();
  34. }
  35. /// <summary>
  36. /// 将多个文件压缩到一个文件流中,可保存为zip文件,方便于web方式下载
  37. /// </summary>
  38. /// <param name="files">多个文件路径,文件或文件夹,或网络路径http/https</param>
  39. /// <param name="rootdir"></param>
  40. /// <returns>文件流</returns>
  41. public MemoryStream ZipStream(List<string> files, string rootdir = "")
  42. {
  43. using (var archive = CreateZipArchive(files, rootdir))
  44. {
  45. var ms = new MemoryStream();
  46. archive.SaveTo(ms, new WriterOptions(CompressionType.Deflate)
  47. {
  48. LeaveStreamOpen = true,
  49. ArchiveEncoding = new ArchiveEncoding()
  50. {
  51. Default = Encoding.UTF8
  52. }
  53. });
  54. return ms;
  55. }
  56. }
  57. /// <summary>
  58. /// 压缩多个文件
  59. /// </summary>
  60. /// <param name="files">多个文件路径,文件或文件夹</param>
  61. /// <param name="zipFile">压缩到...</param>
  62. /// <param name="rootdir">压缩包内部根文件夹</param>
  63. public void Zip(List<string> files, string zipFile, string rootdir = "")
  64. {
  65. using (var archive = CreateZipArchive(files, rootdir))
  66. {
  67. archive.SaveTo(zipFile, new WriterOptions(CompressionType.Deflate)
  68. {
  69. LeaveStreamOpen = true,
  70. ArchiveEncoding = new ArchiveEncoding()
  71. {
  72. Default = Encoding.UTF8
  73. }
  74. });
  75. }
  76. }
  77. /// <summary>
  78. /// 解压rar文件
  79. /// </summary>
  80. /// <param name="rar">rar文件</param>
  81. /// <param name="dir">解压到...</param>
  82. /// <param name="ignoreEmptyDir">忽略空文件夹</param>
  83. public void UnRar(string rar, string dir = "", bool ignoreEmptyDir = true)
  84. {
  85. if (string.IsNullOrEmpty(dir))
  86. {
  87. dir = Path.GetDirectoryName(rar);
  88. }
  89. using (var archive = RarArchive.Open(rar))
  90. {
  91. var entries = ignoreEmptyDir ? archive.Entries.Where(entry => !entry.IsDirectory) : archive.Entries;
  92. foreach (var entry in entries)
  93. {
  94. entry.WriteToDirectory(dir, new ExtractionOptions()
  95. {
  96. ExtractFullPath = true,
  97. Overwrite = true
  98. });
  99. }
  100. }
  101. }
  102. /// <summary>
  103. /// 解压文件,自动检测压缩包类型
  104. /// </summary>
  105. /// <param name="compressedFile">rar文件</param>
  106. /// <param name="dir">解压到...</param>
  107. /// <param name="ignoreEmptyDir">忽略空文件夹</param>
  108. public void Decompress(string compressedFile, string dir = "", bool ignoreEmptyDir = true)
  109. {
  110. if (string.IsNullOrEmpty(dir))
  111. {
  112. dir = Path.GetDirectoryName(compressedFile);
  113. }
  114. using (Stream stream = File.OpenRead(compressedFile))
  115. {
  116. using (var reader = ReaderFactory.Open(stream))
  117. {
  118. while (reader.MoveToNextEntry())
  119. {
  120. if (ignoreEmptyDir)
  121. {
  122. reader.WriteEntryToDirectory(dir, new ExtractionOptions()
  123. {
  124. ExtractFullPath = true,
  125. Overwrite = true
  126. });
  127. }
  128. else
  129. {
  130. if (!reader.Entry.IsDirectory)
  131. {
  132. reader.WriteEntryToDirectory(dir, new ExtractionOptions()
  133. {
  134. ExtractFullPath = true,
  135. Overwrite = true
  136. });
  137. }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// 创建zip包
  145. /// </summary>
  146. /// <param name="files"></param>
  147. /// <param name="rootdir"></param>
  148. /// <returns></returns>
  149. private ZipArchive CreateZipArchive(List<string> files, string rootdir)
  150. {
  151. var archive = ZipArchive.Create();
  152. var dic = GetFileEntryMaps(files);
  153. var remoteFiles = files.Where(s => s.StartsWith("http")).ToList();
  154. foreach (var fileEntry in dic)
  155. {
  156. archive.AddEntry(Path.Combine(rootdir, fileEntry.Value), fileEntry.Key);
  157. }
  158. if (remoteFiles.Any())
  159. {
  160. //var paths = remoteFiles.Select(s => new Uri(s).PathAndQuery).ToList();
  161. //string pathname = new string(paths.First().Substring(0, paths.Min(s => s.Length)).TakeWhile((c, i) => paths.All(s => s[i] == c)).ToArray());
  162. //Dictionary<string, string> pathDic = paths.ToDictionary(s => s, s => s.Substring(pathname.Length));
  163. Parallel.ForEach(remoteFiles, url =>
  164. {
  165. if (_memoryCache.TryGetValue(url, out Stream ms))
  166. {
  167. archive.AddEntry(Path.Combine(rootdir, Path.GetFileName(new Uri(url).AbsolutePath.Trim('/'))), ms);
  168. }
  169. else
  170. {
  171. _httpClient.GetAsync(url).ContinueWith(async t =>
  172. {
  173. if (t.IsCompleted)
  174. {
  175. var res = await t;
  176. if (res.IsSuccessStatusCode)
  177. {
  178. Stream stream = await res.Content.ReadAsStreamAsync();
  179. archive.AddEntry(Path.Combine(rootdir, Path.GetFileName(new Uri(url).AbsolutePath.Trim('/'))), stream);
  180. if (EnableCache)
  181. {
  182. _memoryCache.Set(url, stream, TimeSpan.FromMinutes(10));
  183. }
  184. }
  185. }
  186. }).Wait();
  187. }
  188. });
  189. }
  190. return archive;
  191. }
  192. /// <summary>
  193. /// 获取文件路径和zip-entry的映射
  194. /// </summary>
  195. /// <param name="files"></param>
  196. /// <returns></returns>
  197. private Dictionary<string, string> GetFileEntryMaps(List<string> files)
  198. {
  199. List<string> fileList = new List<string>();
  200. void GetFilesRecurs(string path)
  201. {
  202. //遍历目标文件夹的所有文件
  203. foreach (string fileName in Directory.GetFiles(path))
  204. {
  205. fileList.Add(fileName);
  206. }
  207. //遍历目标文件夹的所有文件夹
  208. foreach (string directory in Directory.GetDirectories(path))
  209. {
  210. GetFilesRecurs(directory);
  211. }
  212. }
  213. files.Where(s => !s.StartsWith("http")).ForEach(s =>
  214. {
  215. if (Directory.Exists(s))
  216. {
  217. GetFilesRecurs(s);
  218. }
  219. else
  220. {
  221. fileList.Add(s);
  222. }
  223. });
  224. if (!fileList.Any())
  225. {
  226. return new Dictionary<string, string>();
  227. }
  228. string dirname = new string(fileList.First().Substring(0, fileList.Min(s => s.Length)).TakeWhile((c, i) => fileList.All(s => s[i] == c)).ToArray());
  229. Dictionary<string, string> dic = fileList.ToDictionary(s => s, s => s.Substring(dirname.Length));
  230. return dic;
  231. }
  232. }
  233. /// <summary>
  234. /// SharpZip
  235. /// </summary>
  236. public static class SharpZip
  237. {
  238. #region 文件压缩
  239. /// <summary>
  240. /// 文件压缩
  241. /// </summary>
  242. /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
  243. /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
  244. [Obsolete("该方法已过时,请使用SevenZipCompressor.Zip方法替代")]
  245. public static void PackFiles(string filename, string directory)
  246. {
  247. throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Zip方法替代");
  248. }
  249. /// <summary>
  250. /// 文件压缩
  251. /// </summary>
  252. /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
  253. /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
  254. [Obsolete("该方法已过时,请使用SevenZipCompressor.Zip方法替代")]
  255. public static async void PackFilesAsync(string filename, string directory)
  256. {
  257. await Task.Delay(0);
  258. throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Zip方法替代");
  259. }
  260. #endregion
  261. #region 文件解压缩
  262. /// <summary>
  263. /// 文件解压缩
  264. /// </summary>
  265. /// <param name="file">待解压文件名(包含物理路径)</param>
  266. /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
  267. [Obsolete("该方法已过时,请使用SevenZipCompressor.Decompress方法替代")]
  268. public static bool UnpackFiles(string file, string dir)
  269. {
  270. throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Decompress方法替代");
  271. }
  272. /// <summary>
  273. /// 文件解压缩
  274. /// </summary>
  275. /// <param name="file">待解压文件名(包含物理路径)</param>
  276. /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
  277. [Obsolete("该方法已过时,请使用SevenZipCompressor.Decompress方法替代")]
  278. public static async Task<bool> UnpackFilesAsync(string file, string dir)
  279. {
  280. await Task.Delay(0);
  281. throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Decompress方法替代");
  282. }
  283. #endregion
  284. }
  285. /// <summary>
  286. /// ClassZip
  287. /// </summary>
  288. public static class ClassZip
  289. {
  290. #region 压缩
  291. /// <summary>
  292. /// 压缩
  293. /// </summary>
  294. /// <param name="fileToZip">待压缩的文件目录或文件</param>
  295. /// <param name="zipedFile">生成的目标文件</param>
  296. /// <param name="level">压缩级别,默认值6</param>
  297. [Obsolete("该方法已过时,请使用SevenZipCompressor.Zip方法替代")]
  298. public static bool Zip(string fileToZip, string zipedFile, int level = 6)
  299. {
  300. throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Zip方法替代");
  301. }
  302. /// <summary>
  303. /// 将多个文件压缩到一个文件流中,可保存为zip文件,方便于web方式下载
  304. /// </summary>
  305. /// <param name="files">多个文件路径,文件或文件夹</param>
  306. /// <returns>文件流</returns>
  307. [Obsolete("该方法已过时,请使用SevenZipCompressor.ZipStream方法替代")]
  308. public static byte[] ZipStream(List<string> files)
  309. {
  310. throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.ZipStream方法替代");
  311. }
  312. #endregion
  313. #region 解压
  314. /// <summary>
  315. /// 解压
  316. /// </summary>
  317. /// <param name="fileToUpZip">待解压的文件</param>
  318. /// <param name="zipedFolder">解压目标存放目录</param>
  319. [Obsolete("该方法已过时,请使用SevenZipCompressor.Decompress方法替代")]
  320. public static void UnZip(string fileToUpZip, string zipedFolder)
  321. {
  322. throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Decompress方法替代");
  323. }
  324. #endregion
  325. }
  326. /// <summary>
  327. /// WinRAR压缩操作
  328. /// </summary>
  329. public static class WinrarHelper
  330. {
  331. #region 压缩
  332. /// <summary>
  333. /// 压缩
  334. /// </summary>
  335. /// <param name="zipname">要解压的文件名</param>
  336. /// <param name="zippath">要压缩的文件目录</param>
  337. /// <param name="dirpath">初始目录</param>
  338. public static void Rar(string zipname, string zippath, string dirpath)
  339. {
  340. _theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
  341. if (_theReg != null)
  342. {
  343. _theObj = _theReg.GetValue("");
  344. _theRar = _theObj.ToString();
  345. _theReg?.Close();
  346. }
  347. _theRar = _theRar.Substring(1, _theRar.Length - 7);
  348. _theInfo = " a " + zipname + " " + zippath;
  349. _theStartInfo = new ProcessStartInfo
  350. {
  351. FileName = _theRar,
  352. Arguments = _theInfo,
  353. WindowStyle = ProcessWindowStyle.Hidden,
  354. WorkingDirectory = dirpath
  355. };
  356. _theProcess = new Process
  357. {
  358. StartInfo = _theStartInfo
  359. };
  360. _theProcess.Start();
  361. }
  362. #endregion
  363. #region 解压缩
  364. /// <summary>
  365. /// 解压缩
  366. /// </summary>
  367. /// <param name="zipname">要解压的文件名</param>
  368. /// <param name="zippath">要解压的文件路径</param>
  369. public static void UnRar(string zipname, string zippath)
  370. {
  371. _theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
  372. if (_theReg != null)
  373. {
  374. _theObj = _theReg.GetValue("");
  375. _theRar = _theObj.ToString();
  376. _theReg.Close();
  377. }
  378. _theRar = _theRar.Substring(1, _theRar.Length - 7);
  379. _theInfo = " X " + zipname + " " + zippath;
  380. _theStartInfo = new ProcessStartInfo
  381. {
  382. FileName = _theRar,
  383. Arguments = _theInfo,
  384. WindowStyle = ProcessWindowStyle.Hidden
  385. };
  386. _theProcess = new Process
  387. {
  388. StartInfo = _theStartInfo
  389. };
  390. _theProcess.Start();
  391. }
  392. #endregion
  393. #region 私有变量
  394. private static string _theRar;
  395. private static RegistryKey _theReg;
  396. private static object _theObj;
  397. private static string _theInfo;
  398. private static ProcessStartInfo _theStartInfo;
  399. private static Process _theProcess;
  400. #endregion
  401. }
  402. }