FileUtils.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. using FileStream fileStream = OpenCreate(PathUtils.WithLongPath(filePath));
  36. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  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 (toRecycleBin) {
  46. if (Exists(filePath)) 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. ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
  78. var thread = new Thread(() => { try { Run(target); } catch (Exception ex) { internalEx = ExceptionDispatchInfo.Capture(ex); } });
  79. thread.SetApartmentState(ApartmentState.STA);
  80. thread.Start();
  81. thread.Join();
  82. internalEx?.Throw();
  83. }
  84. }
  85. // 用于删除到回收站的接口
  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 OpenRead(string filePath) {
  121. return new(PathUtils.WithLongPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  122. }
  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. return File.Exists(PathUtils.WithLongPath(filePath));
  136. }
  137. /// <summary>
  138. /// 创建 <see cref="FileInfo"/> 对象。
  139. /// </summary>
  140. public static FileInfo GetInfo(string path) {
  141. return new(PathUtils.WithLongPath(path));
  142. }
  143. /// <summary>
  144. /// 复制文件。
  145. /// 会创建对应文件夹、覆盖已有的文件。
  146. /// </summary>
  147. public static void Copy(string sourceFilePath, string destFilePath) {
  148. if (sourceFilePath == destFilePath) return; // 如果复制同一个文件则跳过
  149. DirectoryUtils.Create(destFilePath, isFilePath: true);
  150. File.Copy(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath), true);
  151. }
  152. /// <summary>
  153. /// 剪切文件。
  154. /// 会创建对应文件夹、覆盖已有的文件。
  155. /// </summary>
  156. public static void Move(string sourceFilePath, string destFilePath) {
  157. if (sourceFilePath == destFilePath) return; // 如果移动同一个文件则跳过
  158. DirectoryUtils.Create(destFilePath, isFilePath: true);
  159. File.Move(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath));
  160. }
  161. }