FilePackageTool.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. //************************************************************************
  2. // https://github.com/yuzhengyang
  3. // author: yuzhengyang
  4. // date: 2017.6.10 - 2017.6.15
  5. // desc: 文件打包工具
  6. // Copyright (c) yuzhengyang. All rights reserved.
  7. //************************************************************************
  8. using System;
  9. using System.Collections;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Resources;
  14. using System.Runtime.Serialization.Formatters.Binary;
  15. using System.Text;
  16. using Y.Utils.DataUtils.Collections;
  17. using Y.Utils.DelegateUtils;
  18. using Y.Utils.IOUtils.PathUtils;
  19. namespace Y.Utils.IOUtils.FileUtils
  20. {
  21. /// <summary>
  22. /// 文件打包工具
  23. /// </summary>
  24. public class FilePackageTool
  25. {
  26. const string FileType = "Y.Utils.FilePackage";//文件类型 禁止修改长度(19位)
  27. const string FileVersion = "100001";//类型的版本 禁止修改长度(6位)
  28. private static int FileBuffer = 1024 * 1024;
  29. /// <summary>
  30. /// 文件打包
  31. /// </summary>
  32. /// <param name="srcPath">要打包的路径</param>
  33. /// <param name="dstFile">打包后的文件</param>
  34. /// <param name="progress">回调进度</param>
  35. /// <param name="overwrite">覆盖打包后的文件(重复时)</param>
  36. /// <returns>
  37. /// -11;//要打包的路径不存在
  38. /// -12;//打包后的目标文件已存在
  39. /// -13;//要打包的路径中没有文件
  40. /// -14;//输出文件夹不存在
  41. /// -404;//未知错误,操作失败
  42. /// </returns>
  43. public static int Pack(string srcPath, string dstFile, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true)
  44. {
  45. DateTime beginTime = DateTime.Now;
  46. if (!Directory.Exists(srcPath)) return -11;//要打包的路径不存在
  47. if (File.Exists(dstFile) && !overwrite) return -12;//打包后的目标文件已存在
  48. if (!DirTool.Create(DirTool.GetFilePath(dstFile))) return -14;//输出文件夹不存在
  49. List<string> tempfiles = FileTool.GetAllFile(srcPath);
  50. List<FilePackageModel> files = CreateFilePackageModel(tempfiles, srcPath);
  51. if (ListTool.HasElements(files))
  52. {
  53. long allfilesize = files.Sum(x => x.Size);//文件总大小
  54. long surplusfilesize = allfilesize;//剩余要写入的文件大小
  55. using (FileStream fsWrite = new FileStream(dstFile, FileMode.Create))
  56. {
  57. try
  58. {
  59. //写入文件类型标识和版本号
  60. byte[] filetypeandversion = Encoding.Default.GetBytes(FileType + FileVersion);
  61. fsWrite.Write(filetypeandversion, 0, filetypeandversion.Length);
  62. //写入头部总长度
  63. int headl = files.Sum(x => x.AllByteLength);
  64. byte[] headlength = BitConverter.GetBytes(headl);
  65. fsWrite.Write(headlength, 0, headlength.Length);
  66. //循环写入文件信息
  67. files.ForEach(x =>
  68. {
  69. fsWrite.Write(x.NameLengthByte, 0, x.NameLengthByte.Length);
  70. fsWrite.Write(x.NameByte, 0, x.NameByte.Length);
  71. fsWrite.Write(x.PathLengthByte, 0, x.PathLengthByte.Length);
  72. fsWrite.Write(x.PathByte, 0, x.PathByte.Length);
  73. fsWrite.Write(x.SizeLengthByte, 0, x.SizeLengthByte.Length);
  74. fsWrite.Write(x.SizeByte, 0, x.SizeByte.Length);
  75. fsWrite.Write(x.MD5LengthByte, 0, x.MD5LengthByte.Length);
  76. fsWrite.Write(x.MD5Byte, 0, x.MD5Byte.Length);
  77. });
  78. //循环写入文件
  79. files.ForEach(x =>
  80. {
  81. //读取文件(可访问被打开的exe文件)
  82. using (FileStream fsRead = new FileStream(DirTool.Combine(srcPath, x.Path, x.Name), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  83. {
  84. int readCount = 0;
  85. byte[] buffer = new byte[FileBuffer];
  86. while ((readCount = fsRead.Read(buffer, 0, buffer.Length)) > 0)
  87. {
  88. fsWrite.Write(buffer, 0, readCount);
  89. surplusfilesize -= readCount;
  90. progress?.Invoke(sender, new ProgressEventArgs(allfilesize - surplusfilesize, allfilesize));
  91. }
  92. }
  93. });
  94. }
  95. catch (Exception e) { }
  96. }
  97. if (surplusfilesize == 0)
  98. {
  99. return (int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds);//操作成功
  100. }
  101. }
  102. else
  103. {
  104. return -13;//要打包的路径中没有文件
  105. }
  106. //打包失败后,删除打包后的文件
  107. try { File.Delete(dstFile); } catch (Exception e) { }
  108. return -404;//未知错误,操作失败
  109. }
  110. /// <summary>
  111. /// 拆包
  112. /// </summary>
  113. /// <param name="srcFile">包文件路径</param>
  114. /// <param name="dstPath">拆包到的目录 </param>
  115. /// <param name="progress">回调进度</param>
  116. /// <param name="overwrite">覆盖拆包后的文件(重复时)</param>
  117. /// <returns>
  118. /// -11; //要解包的文件不存在
  119. /// -12;//要解包的目标文件夹已存在
  120. /// -20;// 文件类型不匹配
  121. /// -99;//未知错误,操作失败
  122. /// </returns>
  123. public static int Unpack(string srcFile, string dstPath, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true)
  124. {
  125. DateTime beginTime = DateTime.Now;
  126. if (!File.Exists(srcFile)) return -11; //要解包的文件不存在
  127. if (Directory.Exists(dstPath) && !overwrite) return -12;//要解包的目标文件夹已存在
  128. using (FileStream fsRead = new FileStream(srcFile, FileMode.Open))
  129. {
  130. try
  131. {
  132. string version = GetFileVersion(fsRead);
  133. if (version == null) return -20;// 文件类型不匹配
  134. //读取头部总长度
  135. byte[] headl = new byte[4];
  136. int headlength = 0;
  137. fsRead.Read(headl, 0, headl.Length);
  138. headlength = BitConverter.ToInt32(headl, 0);
  139. if (headlength > 0)
  140. {
  141. //读取文件列表信息
  142. byte[] headdata = new byte[headlength];
  143. fsRead.Read(headdata, 0, headlength);
  144. List<FilePackageModel> files = GetFilePackageModel(headdata);
  145. if (ListTool.HasElements(files))
  146. {
  147. long allfilesize = files.Sum(x => x.Size);//文件总大小
  148. long current = 0;//当前进度
  149. //读取写出所有文件
  150. files.ForEach(x =>
  151. {
  152. if (DirTool.Create(DirTool.Combine(dstPath, x.Path)))
  153. {
  154. try
  155. {
  156. using (FileStream fsWrite = new FileStream(DirTool.Combine(dstPath, x.Path, x.Name), FileMode.Create))
  157. {
  158. long size = x.Size;
  159. int readCount = 0;
  160. byte[] buffer = new byte[FileBuffer];
  161. while (size > FileBuffer)
  162. {
  163. readCount = fsRead.Read(buffer, 0, buffer.Length);
  164. fsWrite.Write(buffer, 0, readCount);
  165. size -= readCount;
  166. current += readCount;
  167. progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize));
  168. }
  169. if (size <= FileBuffer)
  170. {
  171. readCount = fsRead.Read(buffer, 0, (int)size);
  172. fsWrite.Write(buffer, 0, readCount);
  173. current += readCount;
  174. progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize));
  175. }
  176. }
  177. }
  178. catch (Exception e)
  179. {
  180. fsRead.Seek(x.Size, SeekOrigin.Current);
  181. current += x.Size;
  182. progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize));
  183. }
  184. }
  185. });
  186. //验证文件列表
  187. bool allCheck = true;
  188. foreach (var file in files)
  189. {
  190. string temp = DirTool.Combine(dstPath, file.Path, file.Name);
  191. string tempCk = FileTool.GetMD5(temp);
  192. if (tempCk != file.MD5)//验证文件(Size:速度会快一些,MD5在大文件的验证上非常耗时)
  193. {
  194. allCheck = false;
  195. break;
  196. }
  197. }
  198. if (allCheck) return (int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds);//操作成功
  199. }
  200. }
  201. }
  202. catch (Exception e) { }
  203. }
  204. return -99;//未知错误,操作失败
  205. }
  206. /// <summary>
  207. /// 获取文件类型的类型版本
  208. /// </summary>
  209. /// <param name="fs"></param>
  210. /// <returns>
  211. /// 如果文件类型不匹配,则返回null
  212. /// </returns>
  213. private static string GetFileVersion(FileStream fs)
  214. {
  215. string result = null;
  216. try
  217. {
  218. //读取文件类型标识和版本号
  219. byte[] filetype = Encoding.Default.GetBytes(FileType);
  220. fs.Read(filetype, 0, filetype.Length);
  221. string filetypestr = Encoding.Default.GetString(filetype);
  222. byte[] fileversion = Encoding.Default.GetBytes(FileVersion);
  223. fs.Read(fileversion, 0, fileversion.Length);
  224. string fileversionstr = Encoding.Default.GetString(fileversion);
  225. //如果文件类型匹配,则返回版本号
  226. if (filetypestr == FileType) result = fileversionstr;
  227. }
  228. catch (Exception e) { }
  229. return result;
  230. }
  231. /// <summary>
  232. /// 解析打包文件文件列表
  233. /// </summary>
  234. /// <param name="headdata"></param>
  235. /// <returns></returns>
  236. private static List<FilePackageModel> GetFilePackageModel(byte[] headdata)
  237. {
  238. List<FilePackageModel> files = new List<FilePackageModel>();
  239. int index = 0;
  240. try
  241. {
  242. while (index < headdata.Length)
  243. {
  244. #region 读取文件名长度和内容
  245. //文件名长度
  246. byte[] namelengthbyte = new byte[4];
  247. Buffer.BlockCopy(headdata, index, namelengthbyte, 0, namelengthbyte.Length);
  248. int namelength = BitConverter.ToInt32(namelengthbyte, 0);
  249. index += namelengthbyte.Length;
  250. //文件名内容
  251. byte[] namebyte = new byte[namelength];
  252. Buffer.BlockCopy(headdata, index, namebyte, 0, namelength);
  253. string name = Encoding.Default.GetString(namebyte);
  254. index += namebyte.Length;
  255. #endregion
  256. #region 读取路径长度和内容
  257. //路径长度
  258. byte[] pathlengthbyte = new byte[4];
  259. Buffer.BlockCopy(headdata, index, pathlengthbyte, 0, pathlengthbyte.Length);
  260. int pathlength = BitConverter.ToInt32(pathlengthbyte, 0);
  261. index += pathlengthbyte.Length;
  262. //路径内容
  263. byte[] pathbyte = new byte[pathlength];
  264. Buffer.BlockCopy(headdata, index, pathbyte, 0, pathlength);
  265. string path = Encoding.Default.GetString(pathbyte);
  266. index += pathbyte.Length;
  267. #endregion
  268. #region 读取文件大小长度和内容
  269. //文件大小长度
  270. byte[] sizelengthbyte = new byte[4];
  271. Buffer.BlockCopy(headdata, index, sizelengthbyte, 0, sizelengthbyte.Length);
  272. int sizelength = BitConverter.ToInt32(sizelengthbyte, 0);
  273. index += sizelengthbyte.Length;
  274. //文件大小
  275. byte[] sizebyte = new byte[sizelength];
  276. Buffer.BlockCopy(headdata, index, sizebyte, 0, sizelength);
  277. long size = BitConverter.ToInt64(sizebyte, 0);
  278. index += sizebyte.Length;
  279. #endregion
  280. #region 读取文件MD5码长度和内容
  281. //文件大小长度
  282. byte[] md5lengthbyte = new byte[4];
  283. Buffer.BlockCopy(headdata, index, md5lengthbyte, 0, md5lengthbyte.Length);
  284. int md5length = BitConverter.ToInt32(md5lengthbyte, 0);
  285. index += md5lengthbyte.Length;
  286. //文件大小
  287. byte[] md5byte = new byte[md5length];
  288. Buffer.BlockCopy(headdata, index, md5byte, 0, md5length);
  289. string md5 = Encoding.Default.GetString(md5byte);
  290. index += md5byte.Length;
  291. #endregion
  292. files.Add(new FilePackageModel()
  293. {
  294. Name = name,
  295. Path = path,
  296. Size = size,
  297. MD5 = md5,
  298. });
  299. }
  300. return files;
  301. }
  302. catch (Exception e) { return null; }
  303. }
  304. /// <summary>
  305. /// 创建打包文件列表信息
  306. /// </summary>
  307. /// <param name="files"></param>
  308. /// <param name="srcPath"></param>
  309. /// <returns></returns>
  310. private static List<FilePackageModel> CreateFilePackageModel(List<string> files, string srcPath)
  311. {
  312. if (ListTool.IsNullOrEmpty(files)) return null;
  313. List<FilePackageModel> result = new List<FilePackageModel>();
  314. //汇总所有文件
  315. files.ForEach(x =>
  316. {
  317. result.Add(new FilePackageModel()
  318. {
  319. Name = Path.GetFileName(x),
  320. Path = DirTool.GetFilePath(x).Substring(srcPath.Count()),
  321. Size = FileTool.Size(x),
  322. MD5 = FileTool.GetMD5(x),
  323. });
  324. });
  325. return result;
  326. }
  327. }
  328. }