Compress.cs 16 KB

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