FileUtils.cs 16 KB

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