FileUtil.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using UnityEngine;
  8. namespace GFGEditor
  9. {
  10. public class FileUtil
  11. {
  12. public static bool CheckPathInParent(string path, string parent)
  13. {
  14. path = path.Replace('\\', '/');
  15. path = path + "/";
  16. parent = parent.Replace('\\', '/');
  17. parent = parent + "/";
  18. parent = Regex.Replace(parent, "//", "/");
  19. return path.Contains(parent);
  20. }
  21. /// <summary>
  22. ///
  23. /// </summary>
  24. /// <param name="dirPath"></param>
  25. /// <param name="excludeDirs"></param>,路径比须从Asset起,例如"Assets/Res/Effect"
  26. /// <param name="action"></param>
  27. public static void ForeachFileInDir(string dirPath, List<string> excludeDirs, Action<string> action)
  28. {
  29. List<string> excludeDirPaths = new List<string>();
  30. if (excludeDirs != null)
  31. {
  32. foreach (var excDir in excludeDirs)
  33. {
  34. var t = Environment.CurrentDirectory + "/" + excDir;
  35. t = t.Replace('\\', '/');
  36. excludeDirPaths.Add(t);
  37. }
  38. }
  39. var t1 = dirPath.Replace('\\', '/');
  40. if (Directory.Exists(dirPath) && !excludeDirPaths.Contains(t1))
  41. {
  42. var files = Directory.GetFiles(dirPath);
  43. var dirs = Directory.GetDirectories(dirPath);
  44. foreach (var file in files)
  45. {
  46. action?.Invoke(file);
  47. }
  48. foreach (var dir in dirs)
  49. {
  50. ForeachFileInDir(dir, excludeDirs, action);
  51. }
  52. }
  53. }
  54. public static void ForeachDirInDir(string dirPath, Action<string> action)
  55. {
  56. if (Directory.Exists(dirPath))
  57. {
  58. var dirs = Directory.GetDirectories(dirPath);
  59. foreach (var dir in dirs)
  60. {
  61. action?.Invoke(dir);
  62. }
  63. }
  64. }
  65. public static List<string> CopyFilesTo(string sourcePath, string targetPath, string saveName, string[] includeExtensionNames = null, string regular = null)
  66. {
  67. List<string> result = new List<string>();
  68. if (Directory.Exists(sourcePath))
  69. {
  70. var files = Directory.GetFiles(sourcePath);
  71. var dirs = Directory.GetDirectories(sourcePath);
  72. foreach (var dir in dirs)
  73. {
  74. List<string> tempResult = CopyFilesTo(dir, targetPath, saveName, includeExtensionNames, regular);
  75. result.AddRange(tempResult);
  76. }
  77. Dictionary<string, string> sourceImageMD5 = new Dictionary<string, string>();
  78. sourceImageMD5 = ImagesClip.ReadSourceImagesMD5(saveName);
  79. foreach (var file in files)
  80. {
  81. var fileName = Path.GetFileName(file);
  82. if (fileName.Trim() == fileName && CheckStringByRegular(fileName, regular))
  83. {
  84. string extensionName = Path.GetExtension(file);
  85. if (includeExtensionNames == null || Array.IndexOf(includeExtensionNames, extensionName) >= 0)
  86. {
  87. if (!sourceImageMD5.ContainsKey(file) || sourceImageMD5[file] != FileUtil.md5file(file))
  88. {
  89. sourceImageMD5[file] = FileUtil.md5file(file);
  90. }
  91. string targetFilePath = targetPath + fileName;
  92. if (!File.Exists(targetFilePath) || !Equals(file, targetFilePath))
  93. {
  94. File.Copy(file, targetFilePath, true);
  95. result.Add(file);
  96. }
  97. }
  98. }
  99. else
  100. {
  101. Debug.LogError($"请检查文件名 {file}");
  102. }
  103. }
  104. ImagesClip.WriteSourceImagesMD5(sourceImageMD5, saveName);
  105. }
  106. return result;
  107. }
  108. public static bool CheckStringByRegular(string str, string regular)
  109. {
  110. str = Path.GetFileNameWithoutExtension(str);
  111. if (regular == null)//不进行正则检测
  112. {
  113. return true;
  114. }
  115. if (System.Text.RegularExpressions.Regex.IsMatch(str, regular))
  116. {
  117. return true;
  118. }
  119. return false;
  120. }
  121. public static List<string> CopyDirsAndFilesInSubDirTo(string sourcePath, string targetPath, string[] excludeExtensionNames = null, string regular = null)
  122. {
  123. List<string> result = new List<string>();
  124. if (Directory.Exists(sourcePath))
  125. {
  126. var dirs = Directory.GetDirectories(sourcePath);
  127. foreach (var dir in dirs)
  128. {
  129. var dirName = Path.GetFileName(dir);
  130. var currTargetPath = targetPath + dirName + "/";
  131. if (!CheckStringByRegular(dirName, regular)) continue;
  132. if (!Directory.Exists(currTargetPath))
  133. {
  134. Directory.CreateDirectory(currTargetPath);
  135. }
  136. List<string> tempResult = CopyFilesAndDirsTo(dir, currTargetPath, excludeExtensionNames);
  137. result.AddRange(tempResult);
  138. }
  139. }
  140. return result;
  141. }
  142. public static List<string> CopyFilesAndDirsTo(string sourcePath, string targetPath, string[] excludeExtensionNames = null)
  143. {
  144. List<string> result = new List<string>();
  145. if (Directory.Exists(sourcePath))
  146. {
  147. var files = Directory.GetFiles(sourcePath);
  148. var dirs = Directory.GetDirectories(sourcePath);
  149. foreach (var file in files)
  150. {
  151. var fileName = Path.GetFileName(file);
  152. if (fileName.Trim() == fileName)
  153. {
  154. string extensionName = Path.GetExtension(file);
  155. if (!FileNameContainsArrayElement(fileName, excludeExtensionNames))
  156. {
  157. string targetFilePath = targetPath + fileName;
  158. if (!File.Exists(targetFilePath) || !Equals(file, targetFilePath))
  159. {
  160. File.Copy(file, targetFilePath, true);
  161. result.Add(file);
  162. }
  163. }
  164. }
  165. else
  166. {
  167. Debug.LogError($"请检查文件名 {file}");
  168. }
  169. }
  170. foreach (var dir in dirs)
  171. {
  172. var dirName = Path.GetFileName(dir);
  173. var currTargetPath = targetPath + dirName + "/";
  174. if (!Directory.Exists(currTargetPath))
  175. {
  176. Directory.CreateDirectory(currTargetPath);
  177. }
  178. List<string> tempResult = CopyFilesAndDirsTo(dir, currTargetPath, excludeExtensionNames);
  179. result.AddRange(tempResult);
  180. }
  181. }
  182. return result;
  183. }
  184. public static string md5file(string file)
  185. {
  186. try
  187. {
  188. FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
  189. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  190. byte[] retVal = md5.ComputeHash(fs);
  191. fs.Close();
  192. StringBuilder sb = new StringBuilder();
  193. for (int i = 0; i < retVal.Length; i++)
  194. {
  195. sb.Append(retVal[i].ToString("x2"));
  196. }
  197. return sb.ToString();
  198. }
  199. catch (Exception ex)
  200. {
  201. throw new Exception("md5file() fail, error:" + ex.Message);
  202. }
  203. }
  204. public static bool Equals(string fileA, string fileB)
  205. {
  206. return md5file(fileA) == md5file(fileB);
  207. }
  208. public static bool FileNameContainsArrayElement(string fileName, string[] excludeExtensionNames = null)
  209. {
  210. if (excludeExtensionNames != null)
  211. {
  212. foreach (var item in excludeExtensionNames)
  213. {
  214. if (fileName.Contains(item))
  215. {
  216. return true;
  217. }
  218. }
  219. }
  220. return false;
  221. }
  222. public static void DeleteUnnecessaryImage(string targetPath, string[] saveNames)
  223. {
  224. if (saveNames.Length > 0)
  225. {
  226. DeleteUnnecessaryImageMD5(saveNames);
  227. DeleteUnnecessaryImageRes(targetPath, saveNames);
  228. }
  229. if (targetPath == ImportArtResTool.DressUpTargetPath)
  230. {
  231. DeleteUnnecessaryImagePos(ImportArtResTool.DressUpTargetPath);
  232. // DeleteUnnecessaryImageMD5(ImportArtResTool.DressUpMd5FileSaveName);
  233. }
  234. Debug.Log(targetPath + "清除完成");
  235. }
  236. //清除无资源的Md5数据
  237. private static void DeleteUnnecessaryImageMD5(string[] saveNames)
  238. {
  239. for (int j = 0; j < saveNames.Length; j++)
  240. {
  241. string saveName = saveNames[j];
  242. List<string> rKeys = new List<string>();
  243. Dictionary<string, string> sourceResMD5 = new Dictionary<string, string>();
  244. sourceResMD5 = ImagesClip.ReadSourceImagesMD5(saveName);
  245. ICollection keys = sourceResMD5.Keys;
  246. foreach (string key in keys)
  247. {
  248. if (!File.Exists(key))
  249. {
  250. rKeys.Add(key);
  251. }
  252. }
  253. for (int i = 0; i < rKeys.Count; i++)
  254. {
  255. sourceResMD5.Remove(rKeys[i]);
  256. }
  257. ImagesClip.WriteSourceImagesMD5(sourceResMD5, saveName);
  258. }
  259. }
  260. private static void DeleteUnnecessaryImageRes(string targetPath, string[] saveNames)
  261. {
  262. string[] includeExtensionNames = new string[] { ".png", ".jpg" };
  263. if (!Directory.Exists(targetPath))
  264. {
  265. Debug.Log(targetPath + "不存在!!!!!");
  266. return;
  267. }
  268. var files = Directory.GetFiles(targetPath);
  269. foreach (var file in files)//遍历项目中的所有资源
  270. {
  271. if (file.Trim() != file)
  272. {
  273. Debug.LogError($"请检查文件名 {file}");
  274. continue;
  275. }
  276. string fileName = Path.GetFileName(file);
  277. string extensionName = Path.GetExtension(file);
  278. if (extensionName == ".meta" || extensionName == ".bytes") continue;
  279. bool has = false;
  280. for (int i = 0; i < saveNames.Length; i++)
  281. {
  282. string saveName = saveNames[i];
  283. Dictionary<string, string> sourceResMD5 = new Dictionary<string, string>();
  284. sourceResMD5 = ImagesClip.ReadSourceImagesMD5(saveName);
  285. ICollection keys = sourceResMD5.Keys;
  286. foreach (string key in keys)//遍历MD5中记录的所有正式资源路径
  287. {
  288. // if (!File.Exists(key))//记录的路径在正式资源里不存在
  289. // {
  290. string sourceName = Path.GetFileName(key);
  291. if (sourceName == fileName)
  292. {
  293. has = true;
  294. break;
  295. }
  296. }
  297. }
  298. if (!has)
  299. {
  300. var deleteFile = targetPath + fileName;
  301. File.Delete(targetPath + fileName);
  302. //写入删除文件脚本
  303. DeleteFileHelper.AddFile(deleteFile);
  304. }
  305. }
  306. Debug.Log(targetPath + "清除完成!");
  307. }
  308. //清除冗余位置文件
  309. private static void DeleteUnnecessaryImagePos(string targetPath)
  310. {
  311. string[] includeExtensionNames = new string[] { ".png", ".jpg" };
  312. var files = Directory.GetFiles(targetPath);
  313. foreach (var file in files)
  314. {
  315. if (file.Trim() != file)
  316. {
  317. Debug.LogError($"请检查文件名 {file}");
  318. continue;
  319. }
  320. string extensionName = Path.GetExtension(file);
  321. string fileName = Path.GetFileName(file).Split('.')[0]; ;
  322. string targetFilePath = targetPath + fileName;
  323. if (extensionName == ".bytes" && !File.Exists(targetFilePath + includeExtensionNames[0]) && !File.Exists(targetFilePath + includeExtensionNames[1]))
  324. {
  325. var deleteFile = targetPath + Path.GetFileName(file);
  326. File.Delete(deleteFile);
  327. //写入删除文件脚本
  328. DeleteFileHelper.AddFile(deleteFile);
  329. }
  330. }
  331. Debug.Log("位置文件清除完成!");
  332. }
  333. public static void DeleteUnnecessaryAnimation(string localDir, string sourceDirs)
  334. {
  335. if (Directory.Exists(localDir))
  336. {
  337. var localFiles = Directory.GetFiles(localDir);
  338. var localDirs = Directory.GetDirectories(localDir);
  339. var souFiles = Directory.GetFiles(sourceDirs);
  340. var souDirs = Directory.GetDirectories(sourceDirs);
  341. foreach (var lfile in localFiles)
  342. {
  343. var lfileName = Path.GetFileName(lfile);
  344. bool existFile = false;
  345. foreach (var sfile in souFiles)
  346. {
  347. var sfileName = Path.GetFileName(sfile);
  348. if (lfileName == sfileName)
  349. {
  350. existFile = true;
  351. break;
  352. }
  353. }
  354. if (!existFile)
  355. {
  356. File.Delete(lfile);
  357. //写入删除文件脚本
  358. DeleteFileHelper.AddFile(lfile);
  359. }
  360. }
  361. foreach (var lDir in localDirs)
  362. {
  363. string lDirName = Path.GetFileName(lDir);
  364. // if (lDirName == "Card") continue;
  365. bool needDelete = false;
  366. foreach (var sDir in souDirs)
  367. {
  368. string sDirName = Path.GetFileName(sDir);
  369. if (lDirName == sDirName)
  370. {
  371. needDelete = true;
  372. DeleteUnnecessaryAnimation(lDir, sDir);
  373. }
  374. }
  375. if (!needDelete)
  376. {
  377. Directory.Delete(lDir, true);
  378. //写入删除文件脚本
  379. DeleteFileHelper.AddFile(lDir);
  380. }
  381. }
  382. }
  383. }
  384. }
  385. }