FileUtils.cs 13 KB

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