FileUtils.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. using System.IO.Compression;
  2. namespace MeloongCore;
  3. public static class FileUtils {
  4. #region 写入
  5. /// <summary>
  6. /// 写入文件。
  7. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  8. /// </summary>
  9. public static void Write(string filePath, string text, Encoding? encoding = null) {
  10. DirectoryUtils.Create(filePath, isFilePath: true);
  11. File.WriteAllText(PathUtils.WithLongPath(filePath), text, encoding ?? new UTF8Encoding());
  12. }
  13. /// <summary>
  14. /// 写入文件。
  15. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  16. /// </summary>
  17. public static void Write(string filePath, byte[] content) {
  18. DirectoryUtils.Create(filePath, isFilePath: true);
  19. File.WriteAllBytes(PathUtils.WithLongPath(filePath), content);
  20. }
  21. /// <summary>
  22. /// 写入文件。
  23. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  24. /// </summary>
  25. public static void Write(string filePath, IEnumerable<byte> content) {
  26. DirectoryUtils.Create(filePath, isFilePath: true);
  27. File.WriteAllBytes(PathUtils.WithLongPath(filePath), [..content]);
  28. }
  29. /// <summary>
  30. /// 将 <paramref name="stream" /> 写入文件。
  31. /// 会将流的位置主动重置到开头。
  32. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  33. /// </summary>
  34. public static void Write(string filePath, Stream stream) {
  35. using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath));
  36. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  37. stream.CopyTo(fileStream);
  38. }
  39. #endregion
  40. #region 删除
  41. /// <summary>
  42. /// 删除文件。
  43. /// </summary>
  44. public static void Delete(string filePath, bool toRecycleBin = false) {
  45. if (toRecycleBin) {
  46. if (Exists(filePath)) DeleteToRecycleBin(filePath);
  47. } else {
  48. File.Delete(PathUtils.WithLongPath(filePath));
  49. }
  50. }
  51. /// <summary>
  52. /// 将文件或文件夹删除到回收站。
  53. /// </summary>
  54. internal static void DeleteToRecycleBin(string target) {
  55. // 实际的删除方法
  56. static void Run(string filePath) {
  57. IShellItem? item = null;
  58. IFileOperation? op = null;
  59. try {
  60. var iid = typeof(IShellItem).GUID;
  61. Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.WithoutLongPath(filePath), IntPtr.Zero, ref iid, out item));
  62. op = (IFileOperation) new FileOperation();
  63. op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
  64. op.DeleteItem(item, IntPtr.Zero);
  65. op.PerformOperations();
  66. op.GetAnyOperationsAborted(out bool aborted);
  67. if (aborted) throw new OperationCanceledException("Delete operation was aborted.");
  68. } finally {
  69. if (op != null && Marshal.IsComObject(op)) Marshal.FinalReleaseComObject(op);
  70. if (item != null && Marshal.IsComObject(item)) Marshal.FinalReleaseComObject(item);
  71. }
  72. }
  73. // 在 STA 线程中执行删除方法
  74. if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
  75. Run(target);
  76. } else {
  77. System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
  78. var thread = new Thread(() => { try { Run(target); } catch (Exception ex) { internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex); } });
  79. thread.SetApartmentState(ApartmentState.STA);
  80. thread.Start();
  81. thread.Join();
  82. internalEx?.Throw();
  83. }
  84. }
  85. // 用于删除到回收站的接口
  86. [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
  87. static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
  88. [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  89. interface IShellItem { }
  90. [ComImport, Guid("3AD05575-8857-4850-9277-11B85BDB8E09")]
  91. class FileOperation { }
  92. [ComImport, Guid("947AAB5F-0A5C-4C13-B4D6-4BF7836FC9F8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  93. interface IFileOperation {
  94. void Advise(IntPtr pfops, out uint pdwCookie);
  95. void Unadvise(uint dwCookie);
  96. void SetOperationFlags(uint dwOperationFlags);
  97. void SetProgressMessage([MarshalAs(UnmanagedType.LPWStr)] string pszMessage);
  98. void SetProgressDialog(IntPtr popd);
  99. void SetProperties(IntPtr pproparray);
  100. void SetOwnerWindow(IntPtr hwndOwner);
  101. void ApplyPropertiesToItem(IShellItem psiItem);
  102. void ApplyPropertiesToItems(IntPtr punkItems);
  103. void RenameItem(IShellItem psiItem, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName, IntPtr pfopsItem);
  104. void RenameItems(IntPtr pUnkItems, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName);
  105. void MoveItem(IShellItem psiItem, IShellItem psiDestinationFolder, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName, IntPtr pfopsItem);
  106. void MoveItems(IntPtr punkItems, IShellItem psiDestinationFolder);
  107. void CopyItem(IShellItem psiItem, IShellItem psiDestinationFolder, [MarshalAs(UnmanagedType.LPWStr)] string pszCopyName, IntPtr pfopsItem);
  108. void CopyItems(IntPtr punkItems, IShellItem psiDestinationFolder);
  109. void DeleteItem(IShellItem psiItem, IntPtr pfopsItem);
  110. void DeleteItems(IntPtr punkItems);
  111. void NewItem(IShellItem psiDestinationFolder, uint dwFileAttributes, [MarshalAs(UnmanagedType.LPWStr)] string pszName, [MarshalAs(UnmanagedType.LPWStr)] string pszTemplateName, IntPtr pfopsItem);
  112. void PerformOperations();
  113. void GetAnyOperationsAborted([MarshalAs(UnmanagedType.Bool)] out bool pfAnyOperationsAborted);
  114. }
  115. #endregion
  116. #region FileStream
  117. /// <summary>
  118. /// 打开该文件的只读 <see cref="FileStream"/>。
  119. /// </summary>
  120. public static FileStream ReadAsStream(string filePath) {
  121. return new(PathUtils.WithLongPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  122. }
  123. /// <summary>
  124. /// 在指定路径创建文件,并打开 <see cref="FileStream"/>。
  125. /// </summary>
  126. public static FileStream CreateAsStream(string filePath) {
  127. DirectoryUtils.Create(filePath, isFilePath: true);
  128. return new(PathUtils.WithLongPath(filePath), FileMode.Create);
  129. }
  130. #endregion
  131. #region 压缩包
  132. /// <summary>
  133. /// 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  134. /// 会自动创建文件夹。会覆盖已有文件,但不会删除多余文件。
  135. /// 解压时会先尝试 UTF8 编码,失败后换用 GB18030。
  136. /// </summary>
  137. public static void ExtractToDirectory(string compressionFile, string outputDirectory, Action<double>? progressIncrementHandler = null) {
  138. compressionFile = PathUtils.WithLongPath(compressionFile);
  139. DirectoryUtils.Create(outputDirectory);
  140. // 解压 gz(gz 不需要考虑编码)
  141. if (compressionFile.EndsWithF(".gz", true)) {
  142. using var stream = new GZipStream(FileUtils.ReadAsStream(compressionFile), CompressionMode.Decompress);
  143. FileUtils.Write(Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(compressionFile)), stream);
  144. return;
  145. }
  146. // 解压 zip
  147. void ExtractWithEncoding(Encoding encoding) {
  148. using var archive = ZipFile.Open(compressionFile, ZipArchiveMode.Read, encoding);
  149. int entryCount = archive.Entries.Count;
  150. foreach (var entry in archive.Entries) {
  151. if (progressIncrementHandler != null && entryCount > 0) progressIncrementHandler(1.0 / entryCount);
  152. if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
  153. // ZipSlip 修复
  154. string outputFilePath = Path.GetFullPath(Path.Combine(outputDirectory, entry.FullName));
  155. if (!outputFilePath.StartsWithF(PathUtils.WithSeparator(Path.GetFullPath(outputDirectory))))
  156. throw new UnauthorizedAccessException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题");
  157. // 实际的解压
  158. using var entryStream = entry.Open();
  159. FileUtils.Write(outputFilePath, entryStream);
  160. }
  161. }
  162. try { // 尝试两种编码
  163. ExtractWithEncoding(new UTF8Encoding(false, true));
  164. } catch (InvalidDataException) {
  165. ExtractWithEncoding(Encoding.GetEncoding("GB18030"));
  166. }
  167. }
  168. /// <summary>
  169. /// 将指定文件夹的内容打包为一个 zip 压缩包。
  170. /// 会自动创建文件夹。会覆盖已有文件。
  171. /// </summary>
  172. public static void CreateZipFromDirectory(string outputFullPath, string sourceDirectory) {
  173. outputFullPath = PathUtils.WithLongPath(outputFullPath);
  174. sourceDirectory = PathUtils.WithLongPath(sourceDirectory);
  175. DirectoryUtils.Create(outputFullPath, isFilePath: true);
  176. FileUtils.Delete(outputFullPath);
  177. ZipFile.CreateFromDirectory(sourceDirectory, outputFullPath);
  178. }
  179. /// <summary>
  180. /// 将多个文件打包为一个压缩文件,所有文件都会被放在压缩文件的根目录。
  181. /// 会自动创建文件夹。会覆盖已有文件。
  182. /// </summary>
  183. public static void CreateZipFromFiles(string outputFullPath, params string[] sourceFiles) {
  184. outputFullPath = PathUtils.WithLongPath(outputFullPath);
  185. sourceFiles = sourceFiles.Select(PathUtils.WithLongPath).ToArray();
  186. DirectoryUtils.Create(outputFullPath, isFilePath: true);
  187. FileUtils.Delete(outputFullPath);
  188. using var archive = ZipFile.Open(outputFullPath, ZipArchiveMode.Create);
  189. foreach (var source in sourceFiles) {
  190. if (!FileUtils.Exists(source)) throw new FileNotFoundException($"未找到需要被压缩的文件({source})", source);
  191. using var sourceStream = FileUtils.ReadAsStream(source);
  192. using var entryStream = archive.CreateEntry(Path.GetFileName(source), CompressionLevel.Optimal).Open();
  193. sourceStream.CopyTo(entryStream);
  194. }
  195. }
  196. #endregion
  197. /// <summary>
  198. /// 确定指定的文件是否存在。
  199. /// </summary>
  200. public static bool Exists(string filePath) {
  201. return File.Exists(PathUtils.WithLongPath(filePath));
  202. }
  203. /// <summary>
  204. /// 创建 <see cref="FileInfo"/> 对象。
  205. /// </summary>
  206. public static FileInfo GetInfo(string path) {
  207. return new(PathUtils.WithLongPath(path));
  208. }
  209. /// <summary>
  210. /// 复制文件。
  211. /// 会创建对应文件夹、覆盖已有的文件。
  212. /// </summary>
  213. public static void Copy(string sourceFilePath, string destFilePath) {
  214. if (sourceFilePath == destFilePath) return; // 如果复制同一个文件则跳过
  215. DirectoryUtils.Create(destFilePath, isFilePath: true);
  216. File.Copy(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath), true);
  217. }
  218. /// <summary>
  219. /// 剪切文件。
  220. /// 会创建对应文件夹、覆盖已有的文件。
  221. /// </summary>
  222. public static void Move(string sourceFilePath, string destFilePath) {
  223. if (sourceFilePath == destFilePath) return; // 如果移动同一个文件则跳过
  224. DirectoryUtils.Create(destFilePath, isFilePath: true);
  225. File.Move(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath));
  226. }
  227. }