2
0

FileUtils.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. => Write(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text));
  11. /// <summary>
  12. /// 写入文件。
  13. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  14. /// </summary>
  15. public static void Write(string filePath, IEnumerable<byte> content)
  16. => Write(filePath, [.. content]);
  17. /// <summary>
  18. /// 写入文件。
  19. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  20. /// </summary>
  21. public static void Write(string filePath, byte[] content) {
  22. DirectoryUtils.Create(filePath, isFilePath: true);
  23. Logger.Trace(() => $"写入文件:{filePath}({content.Length} 字节)");
  24. File.WriteAllBytes(PathUtils.WithLongPath(filePath), content);
  25. }
  26. /// <summary>
  27. /// 将 <paramref name="stream" /> 写入文件。
  28. /// 会将流的位置主动重置到开头。
  29. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  30. /// </summary>
  31. public static void Write(string filePath, Stream stream) {
  32. using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath));
  33. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  34. Logger.Trace(() => $"写入文件:{filePath}({stream.GetType().Name}{(stream.CanSeek ? $" {stream.Length} 字节" : "")})");
  35. stream.CopyTo(fileStream);
  36. }
  37. #endregion
  38. #region 删除
  39. /// <summary>
  40. /// 删除文件。
  41. /// </summary>
  42. public static void Delete(string filePath, bool toRecycleBin = false) {
  43. if (!FileUtils.Exists(filePath)) return;
  44. Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}");
  45. if (toRecycleBin) {
  46. 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. // API
  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. => new(PathUtils.WithLongPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  122. /// <summary>
  123. /// 在指定路径创建文件,并打开 <see cref="FileStream"/>。
  124. /// </summary>
  125. public static FileStream CreateAsStream(string filePath) {
  126. DirectoryUtils.Create(filePath, isFilePath: true);
  127. Logger.Trace($"创建文件流:{filePath}");
  128. return new(PathUtils.WithLongPath(filePath), FileMode.Create);
  129. }
  130. #endregion
  131. #region 压缩包
  132. /// <summary>
  133. /// 以只读模式打开压缩文件。
  134. /// 会先尝试 UTF8 编码,失败后换用 GB18030 编码。
  135. /// </summary>
  136. public static ZipArchive OpenZip(string zipFilePath) {
  137. ZipArchive TryOpen(Encoding encoding) {
  138. Logger.Trace(() => $"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
  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. try { // 尝试两种编码
  150. return TryOpen(new UTF8Encoding(false, true));
  151. } catch (DecoderFallbackException) {
  152. return TryOpen(Encoding.GetEncoding("GB18030"));
  153. }
  154. } catch (InvalidDataException ex) {
  155. throw new InvalidDataException($"文件不是压缩包,或者文件已损坏({zipFilePath})", ex);
  156. }
  157. }
  158. /// <summary>
  159. /// 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  160. /// 会自动创建文件夹。会覆盖已有文件,但不会删除多余文件。
  161. /// </summary>
  162. /// <param name="progressHandler">参数为已完成的总比例(0~1)。</param>
  163. public static void ExtractToDirectory(string compressionFile, string outputDirectory, Action<double>? progressHandler = null) {
  164. compressionFile = PathUtils.WithLongPath(compressionFile);
  165. DirectoryUtils.Create(outputDirectory);
  166. // 解压 gz(gz 不需要考虑编码)
  167. if (compressionFile.EndsWithF(".gz", true)) {
  168. string outFilePath = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(compressionFile));
  169. Logger.Trace($"解压 gz 文件:{compressionFile} → {outFilePath}");
  170. using var fileStream = FileUtils.ReadAsStream(compressionFile);
  171. using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
  172. FileUtils.Write(outFilePath, gzipStream);
  173. progressHandler?.Invoke(1);
  174. return;
  175. }
  176. // 解压 zip
  177. using var archive = FileUtils.OpenZip(compressionFile);
  178. int totalCount = archive.Entries.Count;
  179. int doneCount = 0;
  180. Logger.Trace($"解压 zip 文件:{compressionFile} → {outputDirectory}(共 {totalCount} 项)");
  181. foreach (var entry in archive.Entries) {
  182. doneCount++;
  183. if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount);
  184. if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
  185. // ZipSlip 修复
  186. string outputFilePath = PathUtils.WithLongPath(Path.GetFullPath(Path.Combine(outputDirectory, entry.FullName)));
  187. if (!outputFilePath.StartsWithF(PathUtils.WithSeparator(PathUtils.WithLongPath(Path.GetFullPath(outputDirectory))), ignoreCase:true))
  188. throw new ZipSlipException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题");
  189. // 实际的解压
  190. using var entryStream = entry.Open();
  191. FileUtils.Write(outputFilePath, entryStream);
  192. }
  193. }
  194. public class ZipSlipException(string message) : Exception(message) {}
  195. /// <summary>
  196. /// 将指定文件夹的内容打包为 zip 文件。
  197. /// 会自动创建文件夹。会覆盖已有文件。
  198. /// </summary>
  199. public static void CreateZipFromDirectory(string outputFullPath, string sourceDirectory) {
  200. outputFullPath = PathUtils.WithLongPath(outputFullPath);
  201. sourceDirectory = PathUtils.WithLongPath(sourceDirectory);
  202. DirectoryUtils.Create(outputFullPath, isFilePath: true);
  203. FileUtils.Delete(outputFullPath);
  204. Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}");
  205. ZipFile.CreateFromDirectory(sourceDirectory, outputFullPath);
  206. }
  207. /// <summary>
  208. /// 将多个文件打包为 zip 文件,所有文件都会被放在压缩文件的根目录。
  209. /// 会自动创建文件夹。会覆盖已有文件。
  210. /// </summary>
  211. public static void CreateZipFromFiles(string outputFullPath, params string[] sourceFiles) {
  212. var sources = new Dictionary<string, string>();
  213. foreach (var source in sourceFiles) {
  214. string fileName = Path.GetFileName(source);
  215. if (sources.ContainsKey(fileName)) throw new ArgumentException($"尝试将多个同文件名的文件放进压缩包中({fileName})", nameof(sourceFiles));
  216. sources.Add(fileName, source);
  217. }
  218. CreateZipFromFiles(outputFullPath, sources);
  219. }
  220. /// <summary>
  221. /// 将多个文件打包为 zip 文件。
  222. /// 会自动创建文件夹。会覆盖已有文件。
  223. /// </summary>
  224. /// <param name="sources">键为 zip 文件下的路径,值为文件的本地路径。</param>
  225. public static void CreateZipFromFiles(string outputFullPath, IDictionary<string, string> sources) {
  226. outputFullPath = PathUtils.WithLongPath(outputFullPath);
  227. DirectoryUtils.Create(outputFullPath, isFilePath: true);
  228. FileUtils.Delete(outputFullPath);
  229. using var archive = ZipFile.Open(outputFullPath, ZipArchiveMode.Create);
  230. Logger.Trace(() => $"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}");
  231. foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.WithLongPath(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal);
  232. }
  233. #endregion
  234. /// <summary>
  235. /// 确定指定的文件是否存在。
  236. /// </summary>
  237. public static bool Exists(string filePath)
  238. => File.Exists(PathUtils.WithLongPath(filePath));
  239. /// <summary>
  240. /// 创建 <see cref="FileInfo"/> 对象。
  241. /// </summary>
  242. public static FileInfo GetInfo(string path)
  243. => new(PathUtils.WithLongPath(path));
  244. /// <summary>
  245. /// 复制文件。
  246. /// 会创建对应文件夹、覆盖已有的文件。
  247. /// </summary>
  248. public static void Copy(string sourceFilePath, string destFilePath) {
  249. if (sourceFilePath == destFilePath) return; // 如果复制同一个文件则跳过
  250. DirectoryUtils.Create(destFilePath, isFilePath: true);
  251. Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
  252. File.Copy(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath), true);
  253. }
  254. /// <summary>
  255. /// 剪切文件。
  256. /// 会创建对应文件夹、覆盖已有的文件。
  257. /// </summary>
  258. public static void Move(string sourceFilePath, string destFilePath) {
  259. if (sourceFilePath == destFilePath) return; // 如果移动同一个文件则跳过
  260. DirectoryUtils.Create(destFilePath, isFilePath: true);
  261. FileUtils.Delete(destFilePath);
  262. Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
  263. File.Move(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath));
  264. }
  265. }