FileUtils.cs 17 KB

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