FileUtils.cs 15 KB

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