FileUtils.cs 26 KB

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