ZipHelper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.IO.Packaging;
  7. using Ionic.Zip;
  8. using Bowin.Common.Log;
  9. using SevenZip;
  10. using System.Collections;
  11. namespace Bowin.Common
  12. {
  13. public class ZIPHelper
  14. {
  15. public static IList<string> ExtractFile(string zipFilePath, string targetPath)
  16. {
  17. IList<string> result = new List<string>();
  18. using (Package zip = Package.Open(zipFilePath, FileMode.OpenOrCreate))
  19. {
  20. var parts = zip.GetParts();
  21. foreach (var part in parts)
  22. {
  23. var stream = part.GetStream();
  24. byte[] buffer = new byte[stream.Length + 100];
  25. long total = 0;
  26. for (int offset = 0; ; )
  27. {
  28. int bytesRead = stream.Read(buffer, offset, 100);
  29. if (bytesRead == 0) break;
  30. offset += bytesRead;
  31. total += bytesRead;
  32. }
  33. string filePath = targetPath + @"\" + Path.GetFileName(part.Uri.LocalPath);
  34. var fileStream = File.Create(filePath);
  35. for (int offset = 0; ; )
  36. {
  37. if (total - (offset + 1) > 100)
  38. {
  39. fileStream.Write(buffer, offset, 100);
  40. offset += 100;
  41. }
  42. else
  43. {
  44. fileStream.Write(buffer, offset, Convert.ToInt32(total - (offset + 1)));
  45. fileStream.Flush();
  46. break;
  47. }
  48. }
  49. result.Add(filePath);
  50. }
  51. }
  52. return result;
  53. }
  54. /// <summary>
  55. /// 解压缩.z文件
  56. /// </summary>
  57. /// <param name="rarFilePath"></param>
  58. /// <returns></returns>
  59. public static IList<string> ExtractZFile(string zFilePath, string outPutPath)
  60. {
  61. LogHelper.WriteLog(LogType.ServiceLog, "----进入ExtractZFile解压方法-----");
  62. IList<string> result = new List<string>();
  63. System.Diagnostics.Process proc = new System.Diagnostics.Process();
  64. string pathOf7Zip = System.Configuration.ConfigurationManager.AppSettings["PathOf7Zip"];
  65. if (System.Web.HttpContext.Current != null)
  66. {
  67. pathOf7Zip = System.Web.HttpContext.Current.Server.MapPath("~/") + pathOf7Zip;
  68. }
  69. else
  70. {
  71. pathOf7Zip = System.AppDomain.CurrentDomain.BaseDirectory + pathOf7Zip;
  72. }
  73. proc.StartInfo.FileName = pathOf7Zip;
  74. proc.StartInfo.CreateNoWindow = true;
  75. proc.StartInfo.UseShellExecute = false;
  76. proc.StartInfo.RedirectStandardOutput = true;
  77. proc.StartInfo.RedirectStandardInput = true;
  78. proc.StartInfo.Arguments = "l " + zFilePath;
  79. LogHelper.WriteLog(LogType.ServiceLog, "----" + proc.StartInfo.Arguments + "-----");
  80. //bool currentIsFile = false;
  81. try
  82. {
  83. proc.Start();
  84. if (proc.StandardOutput.EndOfStream)
  85. {
  86. throw new Exception("系统错误!");
  87. }
  88. //string buffer = proc.StandardOutput.ReadLine();
  89. //if (fileText.IndexOf(".jpg") > 0)
  90. //{
  91. // currentIsFile = !currentIsFile;
  92. // if (currentIsFile)
  93. // {
  94. // LogHelper.WriteLog(LogType.ServiceLog, "----result.ADD:" + outPutPath + @"\" + fileText.Split(' ').Last() + "-----");
  95. // result.Add(outPutPath + @"\" + fileText.Split(' ').Last());
  96. // }
  97. //}
  98. string allbuffer = proc.StandardOutput.ReadToEnd();
  99. proc.WaitForExit();
  100. LogHelper.WriteLog(LogType.ServiceLog, "**allbuffer:" + allbuffer + "**");
  101. var phyIndex = allbuffer.IndexOf("Physical Size");
  102. string tText = allbuffer.Substring(phyIndex);
  103. string Text1 = tText.Substring(tText.IndexOf("\r\n") + 4);
  104. string Text2 = Text1.Substring(Text1.IndexOf("\r\n") + 4);
  105. string Text3 = Text2.Substring(Text2.IndexOf("\r\n") + 4);
  106. string Text4 = Text3.Remove(Text3.LastIndexOf("\r\n"));
  107. string Text5 = Text4.Remove(Text4.LastIndexOf("\r\n"));
  108. string Text6 = Text5.Remove(Text5.LastIndexOf("\r\n"));
  109. string Text7 = Text6.Replace("\r\n", "#");
  110. List<string> fileList = Text7.Split('#').ToList();
  111. foreach (var filestring in fileList)
  112. {
  113. result.Add(outPutPath + @"\" + filestring.Split(' ').Last());
  114. }
  115. //if (!proc.WaitForExit(3600000))
  116. //{
  117. //}
  118. proc = new System.Diagnostics.Process();
  119. proc.StartInfo.FileName = pathOf7Zip;
  120. proc.StartInfo.CreateNoWindow = true;
  121. proc.StartInfo.UseShellExecute = false;
  122. proc.StartInfo.RedirectStandardOutput = false;
  123. proc.StartInfo.RedirectStandardInput = false;
  124. proc.EnableRaisingEvents = true;
  125. proc.StartInfo.Arguments = "e -y -o" + outPutPath + " " + zFilePath;
  126. proc.Start();
  127. proc.WaitForExit();
  128. proc.Close();
  129. }
  130. catch (Exception ex)
  131. {
  132. LogHelper.WriteLog(LogType.ServiceLog, "Error:" + ex.Message);
  133. Exception MyEx = new Exception("解压缩出错!" + ex.Message);
  134. }
  135. foreach (var a in result)
  136. {
  137. LogHelper.WriteLog(LogType.ServiceLog, "----" + a + "-----");
  138. }
  139. proc.Dispose();
  140. return result;
  141. }
  142. public static IList<string> Extract7ZFile(string zFilePath, string outPutPath)
  143. {
  144. using (FileStream istream = new FileStream(zFilePath, FileMode.Open, FileAccess.Read))
  145. {
  146. if (IntPtr.Size == 4)
  147. {
  148. SevenZipCompressor.SetLibraryPath(System.Web.HttpContext.Current.Server.MapPath("~/bin/x86/") + @"7z.dll");
  149. }
  150. else
  151. {
  152. SevenZipCompressor.SetLibraryPath(System.Web.HttpContext.Current.Server.MapPath("~/bin/x64/") + @"7z.dll");
  153. }
  154. SevenZipExtractor extractor = new SevenZipExtractor(istream);
  155. extractor.ExtractArchive(outPutPath); // 全部解压到指定目录
  156. using (FileStream ostream = new FileStream(outPutPath, FileMode.Create, FileAccess.Write))
  157. {
  158. extractor.ExtractFile(0, ostream); // 流式解压指定文件
  159. }
  160. }
  161. return new List<string>();
  162. }
  163. public static List<string> SevenZip_ExtractStream(string zFilePath, string outPutPath)
  164. {
  165. var nameKey = Guid.NewGuid().ToString();
  166. var fileStream = new FileStream(zFilePath, FileMode.Open, FileAccess.Read);
  167. var data = new byte[fileStream.Length];
  168. fileStream.Read(data, 0, data.Length);
  169. // 直接读取 Stream流格式会报错,所以暂时做一个转义(先临时保存)
  170. // Invalid archive: open/read error! Is it encrypted and a wrong password was provided?
  171. // If your archive is an exotic one, it is possible that SevenZipSharp has no signature for its format and thus decided it is TAR by mistake.
  172. var tmpZipFullName = CreateTmpFile(data, nameKey);
  173. if (IntPtr.Size == 4)
  174. {
  175. var path = System.Web.HttpContext.Current.Server.MapPath("~/bin/x86/") + "7z.dll";
  176. SevenZipCompressor.SetLibraryPath(path);
  177. }
  178. else
  179. {
  180. var path = System.Web.HttpContext.Current.Server.MapPath("~/bin/x64/") + @"7z.dll";
  181. SevenZipCompressor.SetLibraryPath(path);
  182. }
  183. using (var zip = new SevenZipExtractor(tmpZipFullName))
  184. {
  185. // 解压所有文件到指定目录
  186. zip.ExtractArchive(outPutPath);
  187. // 解压单个文件到指定目录
  188. // zip.ExtractFiles(targetDirectory, 包内的文件索引或者文件名);
  189. // 包内单个文件读取到字节缓冲区
  190. //foreach (var entry in zip.ArchiveFileData)
  191. //{
  192. // using (var memoryStream = new MemoryStream())
  193. // {
  194. // zip.ExtractFile(entry.FileName, memoryStream);
  195. // var entryBuffer = new byte[memoryStream.Length];
  196. // memoryStream.Position = 0;
  197. // memoryStream.Read(entryBuffer, 0, entryBuffer.Length);
  198. // }
  199. //}
  200. // 解压单个文件到指定目录(允许改文件名,以流方式写入)
  201. //foreach (var entry in zip.ArchiveFileData)
  202. // {
  203. // var newFullName = System.Web.HttpContext.Current.Server.MapPath("~/Content/DownFile6/") + entry.FileName;
  204. // var newPath = Path.GetDirectoryName(newFullName);
  205. // if (!string.IsNullOrWhiteSpace(newPath) && !Directory.Exists(newPath))
  206. // Directory.CreateDirectory(newPath);
  207. // using (var fs = new FileStream(newFullName, FileMode.OpenOrCreate, FileAccess.Write))
  208. // {
  209. // zip.ExtractFile(entry.FileName, fs); // 将包内的文件以流的方式写入
  210. // }
  211. // }
  212. } // enf.of using (var zip = new SevenZipExtractor(tmpZipFullName))
  213. List<string> list = GetAllFilesbyFolder(outPutPath, "*.jpg", true);
  214. return list;
  215. }
  216. private static string CreateTmpFile(byte[] data, string nameKey)
  217. {
  218. // 直接读取 Stream流格式会报错,所以暂时做一个转义(先临时保存)
  219. // Invalid archive: open/read error! Is it encrypted and a wrong password was provided?
  220. // If your archive is an exotic one, it is possible that SevenZipSharp has no signature for its format and thus decided it is TAR by mistake.
  221. var dir = System.Web.HttpContext.Current.Server.MapPath("~/Content/DownFile/");
  222. var baseFolder = dir + Path.DirectorySeparatorChar + "TmpZip" + Path.DirectorySeparatorChar;
  223. if (!System.IO.Directory.Exists(baseFolder))
  224. {
  225. Directory.CreateDirectory(baseFolder);
  226. }
  227. var tmpZipFullName = string.Format("{0}{1}_{2}.zip", baseFolder, DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff"), nameKey);
  228. if (System.IO.File.Exists(tmpZipFullName))
  229. {
  230. System.IO.File.Delete(tmpZipFullName);
  231. }
  232. using (var fs1 = new FileStream(tmpZipFullName, FileMode.Create, FileAccess.Write))
  233. {
  234. fs1.Write(data, 0, data.Length);
  235. }
  236. return tmpZipFullName;
  237. }
  238. /// <summary>
  239. ///
  240. /// </summary>
  241. /// <param name="foldername">文件夹名</param>
  242. /// <param name="filefilter">文件名筛选</param>
  243. /// <param name="iscontainsubfolder">是否读取后代文件夹中的文件</param>
  244. /// <returns></returns>
  245. public static List<string> GetAllFilesbyFolder(string foldername, string filefilter, bool iscontainsubfolder)
  246. {
  247. List<string> resarray = new List<string>();
  248. var files = Directory.GetFiles(foldername, filefilter);
  249. for (int i = 0; i < files.Length; i++)
  250. {
  251. resarray.Add(files[i]);
  252. }
  253. if (iscontainsubfolder)
  254. {
  255. string[] folders = Directory.GetDirectories(foldername);
  256. for (int j = 0; j < folders.Length; j++)
  257. {
  258. //遍历所有文件夹
  259. List<string> temp = GetAllFilesbyFolder(folders[j], filefilter, iscontainsubfolder);
  260. resarray.AddRange(temp);
  261. }
  262. }
  263. return resarray;
  264. }
  265. public static string PackageDirectory(string path)
  266. {
  267. using (ZipFile zipNew = new ZipFile())
  268. {
  269. var pathName = Path.GetFileName(path.TrimEnd('\\'));
  270. var fileInfos = Directory.GetFiles(path);
  271. zipNew.UseUnicodeAsNecessary = true;
  272. //zipNew.
  273. // add this map file into the "images" directory in the zip archive
  274. //zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
  275. //// add the report into a different directory in the archive
  276. //zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
  277. foreach (var fileInfo in fileInfos)
  278. {
  279. zipNew.AlternateEncodingUsage = ZipOption.AsNecessary;
  280. zipNew.AlternateEncoding = Encoding.Unicode;
  281. zipNew.AddFile(fileInfo, @"\");
  282. }
  283. zipNew.Save(pathName + ".zip");
  284. return path.TrimEnd('\\') + "\\" + pathName + ".zip";
  285. }
  286. }
  287. }
  288. }