FileUtils.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. using System.Runtime.ExceptionServices;
  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. DirectoryUtils.Create(filePath, isFilePath: true);
  11. File.WriteAllText(PathUtils.WithLongPath(filePath), text, encoding ?? new UTF8Encoding());
  12. }
  13. /// <summary>
  14. /// 写入文件。
  15. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  16. /// </summary>
  17. public static void Write(string filePath, byte[] content) {
  18. DirectoryUtils.Create(filePath, isFilePath: true);
  19. File.WriteAllBytes(PathUtils.WithLongPath(filePath), content);
  20. }
  21. /// <summary>
  22. /// 写入文件。
  23. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  24. /// </summary>
  25. public static void Write(string filePath, IEnumerable<byte> content) {
  26. DirectoryUtils.Create(filePath, isFilePath: true);
  27. File.WriteAllBytes(PathUtils.WithLongPath(filePath), [..content]);
  28. }
  29. /// <summary>
  30. /// 将 <paramref name="stream" /> 写入文件。
  31. /// 会将流的位置主动重置到开头。
  32. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  33. /// </summary>
  34. public static void Write(string filePath, Stream stream) {
  35. DirectoryUtils.Create(filePath, isFilePath: true);
  36. using FileStream fileStream = OpenCreate(PathUtils.WithLongPath(filePath));
  37. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  38. stream.CopyTo(fileStream);
  39. }
  40. #endregion
  41. #region 删除
  42. /// <summary>
  43. /// 删除文件。
  44. /// </summary>
  45. public static void Delete(string filePath, bool toRecycleBin = false) {
  46. if (toRecycleBin) {
  47. if (Exists(filePath)) DeleteToRecycleBin(filePath);
  48. } else {
  49. File.Delete(PathUtils.WithLongPath(filePath));
  50. }
  51. }
  52. /// <summary>
  53. /// 将文件或文件夹删除到回收站。
  54. /// </summary>
  55. internal static void DeleteToRecycleBin(string target) {
  56. // 实际的删除方法
  57. static void Run(string filePath) {
  58. IShellItem? item = null;
  59. IFileOperation? op = null;
  60. try {
  61. var iid = typeof(IShellItem).GUID;
  62. Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.WithoutLongPath(filePath), IntPtr.Zero, ref iid, out item));
  63. op = (IFileOperation) new FileOperation();
  64. op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
  65. op.DeleteItem(item, IntPtr.Zero);
  66. op.PerformOperations();
  67. op.GetAnyOperationsAborted(out bool aborted);
  68. if (aborted) throw new OperationCanceledException("Delete operation was aborted.");
  69. } finally {
  70. if (op != null && Marshal.IsComObject(op)) Marshal.FinalReleaseComObject(op);
  71. if (item != null && Marshal.IsComObject(item)) Marshal.FinalReleaseComObject(item);
  72. }
  73. }
  74. // 在 STA 线程中执行删除方法
  75. if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
  76. Run(target);
  77. } else {
  78. ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
  79. var thread = new Thread(() => { try { Run(target); } catch (Exception ex) { internalEx = ExceptionDispatchInfo.Capture(ex); } });
  80. thread.SetApartmentState(ApartmentState.STA);
  81. thread.Start();
  82. thread.Join();
  83. internalEx?.Throw();
  84. }
  85. }
  86. // 用于删除到回收站的接口
  87. [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
  88. static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
  89. [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  90. interface IShellItem { }
  91. [ComImport, Guid("3AD05575-8857-4850-9277-11B85BDB8E09")]
  92. class FileOperation { }
  93. [ComImport, Guid("947AAB5F-0A5C-4C13-B4D6-4BF7836FC9F8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  94. interface IFileOperation {
  95. void Advise(IntPtr pfops, out uint pdwCookie);
  96. void Unadvise(uint dwCookie);
  97. void SetOperationFlags(uint dwOperationFlags);
  98. void SetProgressMessage([MarshalAs(UnmanagedType.LPWStr)] string pszMessage);
  99. void SetProgressDialog(IntPtr popd);
  100. void SetProperties(IntPtr pproparray);
  101. void SetOwnerWindow(IntPtr hwndOwner);
  102. void ApplyPropertiesToItem(IShellItem psiItem);
  103. void ApplyPropertiesToItems(IntPtr punkItems);
  104. void RenameItem(IShellItem psiItem, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName, IntPtr pfopsItem);
  105. void RenameItems(IntPtr pUnkItems, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName);
  106. void MoveItem(IShellItem psiItem, IShellItem psiDestinationFolder, [MarshalAs(UnmanagedType.LPWStr)] string pszNewName, IntPtr pfopsItem);
  107. void MoveItems(IntPtr punkItems, IShellItem psiDestinationFolder);
  108. void CopyItem(IShellItem psiItem, IShellItem psiDestinationFolder, [MarshalAs(UnmanagedType.LPWStr)] string pszCopyName, IntPtr pfopsItem);
  109. void CopyItems(IntPtr punkItems, IShellItem psiDestinationFolder);
  110. void DeleteItem(IShellItem psiItem, IntPtr pfopsItem);
  111. void DeleteItems(IntPtr punkItems);
  112. void NewItem(IShellItem psiDestinationFolder, uint dwFileAttributes, [MarshalAs(UnmanagedType.LPWStr)] string pszName, [MarshalAs(UnmanagedType.LPWStr)] string pszTemplateName, IntPtr pfopsItem);
  113. void PerformOperations();
  114. void GetAnyOperationsAborted([MarshalAs(UnmanagedType.Bool)] out bool pfAnyOperationsAborted);
  115. }
  116. #endregion
  117. #region FileStream
  118. /// <summary>
  119. /// 打开该文件的只读 <see cref="FileStream"/>。
  120. /// </summary>
  121. public static FileStream OpenRead(string filePath) =>
  122. new(PathUtils.WithLongPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  123. /// <summary>
  124. /// 在指定路径创建文件,并打开 <see cref="FileStream"/>。
  125. /// </summary>
  126. public static FileStream OpenCreate(string filePath) {
  127. DirectoryUtils.Create(filePath, isFilePath: true);
  128. return new(PathUtils.WithLongPath(filePath), FileMode.Create);
  129. }
  130. #endregion
  131. /// <summary>
  132. /// 确定指定的文件是否存在。
  133. /// </summary>
  134. public static bool Exists(string filePath) =>
  135. File.Exists(PathUtils.WithLongPath(filePath));
  136. /// <summary>
  137. /// 创建 <see cref="FileInfo"/> 对象。
  138. /// </summary>
  139. public static FileInfo GetInfo(string path) =>
  140. new(PathUtils.WithLongPath(path));
  141. /// <summary>
  142. /// 复制文件。
  143. /// 会创建对应文件夹、覆盖已有的文件。
  144. /// </summary>
  145. public static void Copy(string sourceFilePath, string destFilePath) {
  146. if (sourceFilePath == destFilePath) return; // 如果复制同一个文件则跳过
  147. DirectoryUtils.Create(destFilePath, isFilePath: true);
  148. File.Copy(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath), true);
  149. }
  150. /// <summary>
  151. /// 剪切文件。
  152. /// 会创建对应文件夹、覆盖已有的文件。
  153. /// </summary>
  154. public static void Move(string sourceFilePath, string destFilePath) {
  155. if (sourceFilePath == destFilePath) return; // 如果移动同一个文件则跳过
  156. DirectoryUtils.Create(destFilePath, isFilePath: true);
  157. File.Move(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath));
  158. }
  159. }