FileUtils.cs 19 KB

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