FilePackageTool.cs 15 KB

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