2
0

FileUtils.cs 14 KB

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