FileUtils.cs 26 KB

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