FilePackageTool.cs 16 KB

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