FileUtils.cs 19 KB

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