FileUtils.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. using System.IO.Compression;
  2. namespace MeloongCore;
  3. public static class FileUtils {
  4. #region 读取
  5. /// <summary>
  6. /// 打开指定文件的只读 <see cref="Stream"/>。
  7. /// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
  8. /// </summary>
  9. public static Stream ReadAsStream(string filePath, Type? type = null) {
  10. if (type is null) {
  11. return ResilientUtils.RetryOn<IOException, Stream>(() => new FileStream(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
  12. } else {
  13. return type.Assembly.GetManifestResourceStream(filePath) ?? throw new FileNotFoundException($"Embedded resource \"{filePath}\" was not found.");
  14. }
  15. }
  16. /// <summary>
  17. /// 读取文件中的所有内容。
  18. /// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
  19. /// </summary>
  20. public static byte[] ReadAsBytes(string filePath, Type? type = null) {
  21. using Stream fs = FileUtils.ReadAsStream(filePath, type); // 不能使用 File.ReadAllBytes,它不指定 FileShare.ReadWrite,会在文件被占用时抛出异常
  22. using MemoryStream ms = new();
  23. fs.CopyTo(ms);
  24. return ms.ToArray();
  25. }
  26. /// <summary>
  27. /// 读取文件中的所有内容。
  28. /// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
  29. /// </summary>
  30. public static string ReadAsString(string filePath, Encoding? encoding = null, Type? type = null)
  31. => FileUtils.ReadAsBytes(filePath, type).GetString(encoding);
  32. /// <summary>
  33. /// 读取文件中的所有内容。
  34. /// <para/>若文件不存在或读取失败,返回 <see langword="null"/>,而不是抛出异常。
  35. /// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
  36. /// </summary>
  37. public static string? TryReadAsString(string filePath, Encoding? encoding = null, Type? type = null) {
  38. try {
  39. if (type != null && !FileUtils.Exists(filePath)) return null;
  40. return FileUtils.ReadAsBytes(filePath, type).GetString(encoding);
  41. } catch {
  42. return null;
  43. }
  44. }
  45. /// <summary>
  46. /// 读取文件中的所有内容,并按行分割。
  47. /// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
  48. /// </summary>
  49. public static string[] ReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null, Type? type = null)
  50. => FileUtils.ReadAsString(filePath, encoding, type).SplitLines(skipEmptyLines);
  51. /// <summary>
  52. /// 读取文件中的所有内容,并按行分割。
  53. /// <para/>若文件不存在或读取失败,返回空数组,而不是抛出异常。
  54. /// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
  55. /// </summary>
  56. public static string[] TryReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null, Type? type = null)
  57. => FileUtils.TryReadAsString(filePath, encoding, type)?.SplitLines(skipEmptyLines) ?? [];
  58. #endregion
  59. #region 创建 / 写入
  60. /// <summary>
  61. /// 创建文件,并将 <paramref name="text" /> 写入文件。
  62. /// 若文件已存在,则会覆盖原文件。
  63. /// </summary>
  64. public static void Write(string filePath, string text, Encoding? encoding = null)
  65. => FileUtils.Write(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text));
  66. /// <summary>
  67. /// 创建文件,并将 <paramref name="content" /> 写入文件。
  68. /// 若文件已存在,则会覆盖原文件。
  69. /// </summary>
  70. public static void Write(string filePath, IEnumerable<byte> content)
  71. => FileUtils.Write(filePath, [.. content]);
  72. /// <summary>
  73. /// 创建文件,并将 <paramref name="content" /> 写入文件。
  74. /// 若文件已存在,则会覆盖原文件。
  75. /// </summary>
  76. public static void Write(string filePath, byte[] content) {
  77. DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
  78. Logger.Trace($"写入文件:{filePath}({content.Length} 字节)");
  79. ResilientUtils.RetryOn<IOException>(() => {
  80. FileUtils.Delete(filePath);
  81. File.WriteAllBytes(PathUtils.ForApi(filePath), content);
  82. });
  83. }
  84. /// <summary>
  85. /// 创建文件,并将 <paramref name="stream" /> 写入文件。
  86. /// 会将流的位置主动重置到开头。
  87. /// 若文件已存在,则会覆盖原文件。
  88. /// </summary>
  89. public static void Write(string filePath, Stream stream) {
  90. ResilientUtils.RetryOn<IOException>(() => {
  91. FileUtils.Delete(filePath);
  92. using FileStream fileStream = FileUtils.CreateAsStream(filePath);
  93. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  94. Logger.Trace($"写入文件:{filePath}({stream.GetType().Name}{(stream.CanSeek ? $" {stream.Length} 字节" : "")})");
  95. stream.CopyTo(fileStream);
  96. });
  97. }
  98. /// <summary>
  99. /// 创建文件,并打开 <see cref="FileStream"/>。
  100. /// 若文件已存在,则会覆盖原文件。
  101. /// </summary>
  102. public static FileStream CreateAsStream(string filePath) {
  103. DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
  104. Logger.Trace($"创建文件流:{filePath}");
  105. return ResilientUtils.RetryOn<IOException, FileStream>(() => {
  106. FileUtils.Delete(filePath);
  107. return new FileStream(PathUtils.ForApi(filePath), FileMode.Create);
  108. });
  109. }
  110. /// <summary>
  111. /// 在临时文件夹下创建一个随机名称的文件,并返回其路径。
  112. /// </summary>
  113. public static string CreateRandom()
  114. => ResilientUtils.RetryOn<IOException, string>(Path.GetTempFileName);
  115. #endregion
  116. #region 复制 / 剪切
  117. /// <summary>
  118. /// 复制文件。
  119. /// 会创建对应文件夹、覆盖已有的文件。
  120. /// 若复制自身到自身,则不执行操作;若仅大小写不同,则重命名此文件。
  121. /// </summary>
  122. public static void Copy(string sourceFilePath, string destFilePath) {
  123. sourceFilePath = PathUtils.ForCompare(sourceFilePath);
  124. destFilePath = PathUtils.ForCompare(destFilePath);
  125. if (string.Compare(sourceFilePath, destFilePath, ignoreCase:false) == 0) {
  126. // 复制自身到自身,则不执行操作
  127. Logger.Trace($"复制文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
  128. } else if (string.Compare(sourceFilePath, destFilePath, ignoreCase:true) == 0) {
  129. // 路径仅大小写不同,等效于重命名
  130. Logger.Trace($"复制文件到自身,但大小写不同,等效于重命名文件:{sourceFilePath} → {destFilePath}");
  131. FileUtils.Move(sourceFilePath, destFilePath);
  132. } else {
  133. // 实际的复制
  134. DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
  135. Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
  136. ResilientUtils.RetryOn<IOException>(()
  137. => File.Copy(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath), true));
  138. }
  139. }
  140. /// <summary>
  141. /// 剪切文件。
  142. /// 会创建对应文件夹、覆盖已有的文件。
  143. /// </summary>
  144. public static void Move(string sourceFilePath, string destFilePath) {
  145. sourceFilePath = PathUtils.ForCompare(sourceFilePath);
  146. destFilePath = PathUtils.ForCompare(destFilePath);
  147. if (string.Compare(sourceFilePath, destFilePath, ignoreCase: false) == 0) {
  148. // 剪切自身到自身,则不执行操作
  149. Logger.Trace($"剪切文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
  150. } else if (string.Compare(sourceFilePath, destFilePath, ignoreCase: true) == 0) {
  151. // 路径仅大小写不同
  152. Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
  153. ResilientUtils.RetryOn<IOException>(() => {
  154. var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFilePath), Path.GetRandomFileName());
  155. File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(temp));
  156. File.Move(PathUtils.ForApi(temp), PathUtils.ForApi(destFilePath));
  157. });
  158. } else {
  159. // 实际的剪切
  160. DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
  161. FileUtils.Delete(destFilePath);
  162. Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
  163. ResilientUtils.RetryOn<IOException>(()
  164. => File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath)));
  165. }
  166. }
  167. #endregion
  168. #region 删除
  169. /// <summary>
  170. /// 删除文件。
  171. /// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
  172. /// </summary>
  173. /// <returns>
  174. /// 如果文件不存在,返回 <see langword="null"/>。
  175. /// <para/>如果成功删除到回收站,返回 <see langword="true"/>。
  176. /// <para/>如果永久删除,返回 <see langword="false"/>。
  177. /// </returns>
  178. public static bool? Delete(string filePath, bool toRecycleBin = false) {
  179. if (!FileUtils.Exists(filePath)) return null;
  180. Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}");
  181. // 删除到回收站
  182. if (toRecycleBin) {
  183. try {
  184. DeleteToRecycleBin(filePath);
  185. return true;
  186. } catch (Exception ex) {
  187. Logger.Warn(ex, $"无法将文件删除到回收站,回退到永久删除:{filePath}");
  188. }
  189. }
  190. // 永久删除
  191. ResilientUtils.RetryOn<IOException>(()
  192. => File.Delete(PathUtils.ForApi(filePath)));
  193. return false;
  194. }
  195. /// <summary>
  196. /// 将文件或文件夹删除到回收站。
  197. /// </summary>
  198. internal static void DeleteToRecycleBin(string target) {
  199. // 实际的删除方法
  200. void Run() {
  201. IShellItem? item = null;
  202. IFileOperation? op = null;
  203. try {
  204. var iid = typeof(IShellItem).GUID;
  205. Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.RemoveExtendedPrefix(target), IntPtr.Zero, ref iid, out item));
  206. op = (IFileOperation) new FileOperation();
  207. op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
  208. op.DeleteItem(item, IntPtr.Zero);
  209. op.PerformOperations();
  210. op.GetAnyOperationsAborted(out bool aborted);
  211. if (aborted) throw new OperationCanceledException("Delete operation was aborted.");
  212. } finally {
  213. if (op != null && Marshal.IsComObject(op)) Marshal.FinalReleaseComObject(op);
  214. if (item != null && Marshal.IsComObject(item)) Marshal.FinalReleaseComObject(item);
  215. }
  216. }
  217. // 在 STA 线程中执行删除方法
  218. if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
  219. ResilientUtils.RetryOn<IOException>(Run);
  220. } else {
  221. System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
  222. var thread = new Thread(() => {
  223. try {
  224. ResilientUtils.RetryOn<IOException>(Run);
  225. } catch (Exception ex) {
  226. internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex);
  227. }
  228. }) { IsBackground = true, Name = nameof(DeleteToRecycleBin) };
  229. thread.SetApartmentState(ApartmentState.STA);
  230. thread.Start();
  231. thread.Join();
  232. internalEx?.Throw();
  233. }
  234. }
  235. // API
  236. [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
  237. static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
  238. [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  239. interface IShellItem { }
  240. [ComImport, Guid("3AD05575-8857-4850-9277-11B85BDB8E09")]
  241. class FileOperation { }
  242. [ComImport, Guid("947AAB5F-0A5C-4C13-B4D6-4BF7836FC9F8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  243. interface IFileOperation {
  244. void Advise(IntPtr pfops, out uint pdwCookie);
  245. void Unadvise(uint dwCookie);
  246. void SetOperationFlags(uint dwOperationFlags);
  247. void SetProgressMessage([MarshalAs(UnmanagedType.LPWStr)] string pszMessage);
  248. void SetProgressDialog(IntPtr popd);
  249. void SetProperties(IntPtr pproparray);
  250. void SetOwnerWindow(IntPtr hwndOwner);
  251. void ApplyPropertiesToItem(IShellItem psiItem);
  252. void ApplyPropertiesToItems(IntPtr punkItems);
  253. void RenameItem(IShellItem psiItem, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName, IntPtr pfopsItem);
  254. void RenameItems(IntPtr pUnkItems, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName);
  255. void MoveItem(IShellItem psiItem, IShellItem psiDestinationFolder, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName, IntPtr pfopsItem);
  256. void MoveItems(IntPtr punkItems, IShellItem psiDestinationFolder);
  257. void CopyItem(IShellItem psiItem, IShellItem psiDestinationFolder, [MarshalAs(UnmanagedType.LPWStr)] string pszCopyName, IntPtr pfopsItem);
  258. void CopyItems(IntPtr punkItems, IShellItem psiDestinationFolder);
  259. void DeleteItem(IShellItem psiItem, IntPtr pfopsItem);
  260. void DeleteItems(IntPtr punkItems);
  261. void NewItem(IShellItem psiDestinationFolder, uint dwFileAttributes, [MarshalAs(UnmanagedType.LPWStr)] string pszName, [MarshalAs(UnmanagedType.LPWStr)] string pszTemplateName, IntPtr pfopsItem);
  262. void PerformOperations();
  263. void GetAnyOperationsAborted([MarshalAs(UnmanagedType.Bool)] out bool pfAnyOperationsAborted);
  264. }
  265. #endregion
  266. #region 压缩 / 解压
  267. /// <summary>
  268. /// 以只读模式打开压缩文件。
  269. /// 会先尝试 UTF8 编码,失败后换用 GB18030 编码。
  270. /// </summary>
  271. public static ZipArchive OpenZip(string zipFilePath) {
  272. ZipArchive TryOpen(Encoding encoding) {
  273. Logger.Trace($"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
  274. var result = ZipFile.Open(PathUtils.ForApi(zipFilePath), ZipArchiveMode.Read, encoding);
  275. try {
  276. _ = result.Entries; // 如果编码有误,会在这里抛出 DecoderFallbackException;如果文件异常,会在这里抛出 InvalidDataException
  277. return result;
  278. } catch {
  279. result.Dispose();
  280. throw;
  281. }
  282. }
  283. try {
  284. try { // 尝试两种编码
  285. return TryOpen(new UTF8Encoding(false, true));
  286. } catch (DecoderFallbackException) {
  287. return TryOpen(Encoding.GetEncoding("GB18030"));
  288. }
  289. } catch (InvalidDataException ex) {
  290. throw new InvalidDataException($"文件不是压缩包,或者文件已损坏({zipFilePath})", ex);
  291. }
  292. }
  293. /// <summary>
  294. /// 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  295. /// 会自动创建文件夹。会覆盖已有文件,但不会删除多余文件。
  296. /// </summary>
  297. /// <param name="progressHandler">参数为已完成的总比例(0~1)。</param>
  298. public static void ExtractToDirectory(string compressionFile, string outputDirectory, Action<double>? progressHandler = null) {
  299. compressionFile = PathUtils.ForApi(compressionFile);
  300. DirectoryUtils.Create(outputDirectory);
  301. // 解压 gz(gz 不需要考虑编码)
  302. if (compressionFile.EndsWithF(".gz", true)) {
  303. string outFilePath = Path.Combine(outputDirectory, PathUtils.GetFileNameWithoutExtension(compressionFile));
  304. Logger.Trace($"解压 gz 文件:{compressionFile} → {outFilePath}");
  305. using var fileStream = FileUtils.ReadAsStream(compressionFile);
  306. using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
  307. FileUtils.Write(outFilePath, gzipStream);
  308. progressHandler?.Invoke(1);
  309. return;
  310. }
  311. // 解压 zip
  312. using var archive = FileUtils.OpenZip(compressionFile);
  313. int totalCount = archive.Entries.Count;
  314. int doneCount = 0;
  315. Logger.Trace($"解压 zip 文件:{compressionFile} → {outputDirectory}(共 {totalCount} 项)");
  316. foreach (var entry in archive.Entries) {
  317. doneCount++;
  318. if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount);
  319. if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
  320. // ZipSlip 修复
  321. string outputFilePath = PathUtils.ForCompare(Path.Combine(outputDirectory, entry.FullName));
  322. if (!outputFilePath.StartsWithF(PathUtils.AddSlashSuffix(PathUtils.ForCompare(outputDirectory)), ignoreCase:true))
  323. throw new ZipSlipException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题");
  324. // 实际的解压
  325. using var entryStream = entry.Open();
  326. FileUtils.Write(outputFilePath, entryStream);
  327. }
  328. }
  329. public class ZipSlipException(string message) : Exception(message) {}
  330. /// <summary>
  331. /// 将指定文件夹的内容打包为 zip 文件。
  332. /// 会自动创建文件夹。会覆盖已有文件。
  333. /// </summary>
  334. public static void CreateZipFromDirectory(string outputFullPath, string sourceDirectory) {
  335. DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
  336. FileUtils.Delete(outputFullPath);
  337. Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}");
  338. ResilientUtils.RetryOn<IOException>(()
  339. => ZipFile.CreateFromDirectory(PathUtils.ForApi(sourceDirectory), PathUtils.ForApi(outputFullPath)));
  340. }
  341. /// <summary>
  342. /// 将多个文件打包为 zip 文件,所有文件都会被放在压缩文件的根目录。
  343. /// 会自动创建文件夹。会覆盖已有文件。
  344. /// </summary>
  345. public static void CreateZipFromFiles(string outputFullPath, params string[] sourceFiles) {
  346. var sources = new Dictionary<string, string>();
  347. foreach (var source in sourceFiles) {
  348. string fileName = PathUtils.GetLastPart(source);
  349. if (sources.ContainsKey(fileName)) throw new ArgumentException($"尝试将多个同文件名的文件放进压缩包中({fileName})", nameof(sourceFiles));
  350. sources.Add(fileName, source);
  351. }
  352. FileUtils.CreateZipFromFiles(outputFullPath, sources);
  353. }
  354. /// <summary>
  355. /// 将多个文件打包为 zip 文件。
  356. /// 会自动创建文件夹。会覆盖已有文件。
  357. /// </summary>
  358. /// <param name="sources">键为 zip 文件下的路径,值为文件的本地路径。</param>
  359. public static void CreateZipFromFiles(string outputFullPath, IDictionary<string, string> sources) {
  360. DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
  361. FileUtils.Delete(outputFullPath);
  362. using var archive = ResilientUtils.RetryOn<IOException, ZipArchive>(()
  363. => ZipFile.Open(PathUtils.ForApi(outputFullPath), ZipArchiveMode.Create));
  364. Logger.Trace($"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}");
  365. foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.ForApi(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal);
  366. }
  367. #endregion
  368. /// <summary>
  369. /// 确定指定的文件是否存在。
  370. /// </summary>
  371. public static bool Exists(string filePath)
  372. => File.Exists(PathUtils.ForApi(filePath));
  373. /// <summary>
  374. /// 获取 <see cref="FileInfo"/> 对象。
  375. /// </summary>
  376. public static FileInfo GetInfo(string path)
  377. => new(PathUtils.ForApi(path));
  378. }
  379. public class FileChecker {
  380. /// <summary>
  381. /// 文件的准确大小。
  382. /// <para/>不检查则为 -1。
  383. /// </summary>
  384. public long ActualSize = -1;
  385. /// <summary>
  386. /// 文件的最小大小。
  387. /// <para/>不检查则为 -1。
  388. /// </summary>
  389. public long MinSize = -1;
  390. /// <summary>
  391. /// 文件的 MD5、SHA1、SHA256 或 SHA512。会根据输入字符串的长度自动判断种类。
  392. /// <para/>不检查则为 <c>null</c>。
  393. /// </summary>
  394. public string? Hash = null;
  395. /// <summary>
  396. /// 是否要求为 JSON 文件。
  397. /// </summary>
  398. public bool IsJson = false;
  399. /// <summary>
  400. /// 检查文件。
  401. /// <para/>若成功则返回 <c>null</c>,失败则返回错误的描述文本(文本不以句号结尾)。
  402. /// <para/>不会抛出异常。
  403. /// </summary>
  404. public string? Check(string localPath) {
  405. try {
  406. var info = FileUtils.GetInfo(localPath);
  407. if (!info.Exists) return "文件不存在:" + localPath;
  408. long fileSize = info.Length;
  409. if (ActualSize >= 0 && ActualSize != fileSize) {
  410. return $"文件大小应为 {ActualSize} B,实际为 {fileSize} B" +
  411. (fileSize < 2000 ? ",内容为:" + FileUtils.ReadAsString(localPath) : "");
  412. }
  413. if (MinSize >= 0 && MinSize > fileSize) {
  414. return $"文件大小应至少为 {MinSize} B,实际为 {fileSize} B" +
  415. (fileSize < 2000 ? ",内容为:" + FileUtils.ReadAsString(localPath) : "");
  416. }
  417. string? hash = Hash;
  418. if (!string.IsNullOrEmpty(hash)) {
  419. hash = hash!.Lower();
  420. switch (hash.Length) {
  421. case 32:
  422. string md5 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Md5);
  423. if (hash != md5) return "文件 MD5 应为 " + hash + ",实际为 " + md5;
  424. break;
  425. case 40:
  426. string sha1 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Sha1);
  427. if (hash != sha1) return "文件 SHA1 应为 " + hash + ",实际为 " + sha1;
  428. break;
  429. case 64:
  430. string sha256 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Sha256);
  431. if (hash != sha256) return "文件 SHA256 应为 " + hash + ",实际为 " + sha256;
  432. break;
  433. case 128:
  434. string sha512 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Sha512);
  435. if (hash != sha512) return "文件 SHA512 应为 " + hash + ",实际为 " + sha512;
  436. break;
  437. default:
  438. return $"无法识别的 Hash 类型(长度为 {hash.Length}):{hash}";
  439. }
  440. }
  441. if (IsJson) {
  442. string content = FileUtils.ReadAsString(localPath);
  443. if (content == "") return "读取到的文件为空";
  444. //GetJson(content); // 失败会抛出异常
  445. }
  446. return null;
  447. } catch (Exception ex) {
  448. Logger.Warn(ex, "检查文件出错");
  449. return ex.GetDisplay(false);
  450. }
  451. }
  452. }