FileUtils.cs 17 KB

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