FileUtils.cs 15 KB

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