FileUtils.cs 29 KB

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