FilePackageTool.cs 16 KB

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