FileUtils.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. namespace MeloongCore;
  2. public static class FileUtils {
  3. #region 写入
  4. /// <summary>
  5. /// 写入文件。
  6. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  7. /// </summary>
  8. public static void Write(string filePath, string text, Encoding? encoding = null) {
  9. DirectoryUtils.Create(filePath, isFilePath: true);
  10. File.WriteAllText(PathUtils.ToLongPath(filePath), text, encoding ?? new UTF8Encoding());
  11. }
  12. /// <summary>
  13. /// 写入文件。
  14. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  15. /// </summary>
  16. public static void Write(string filePath, byte[] content) {
  17. DirectoryUtils.Create(filePath, isFilePath: true);
  18. File.WriteAllBytes(PathUtils.ToLongPath(filePath), content);
  19. }
  20. /// <summary>
  21. /// 将 <paramref name="stream" /> 写入文件。
  22. /// 会将流的位置主动重置到开头。
  23. /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
  24. /// </summary>
  25. public static void Write(string filePath, Stream stream) {
  26. DirectoryUtils.Create(filePath, isFilePath: true);
  27. using FileStream fileStream = new(PathUtils.ToLongPath(filePath), FileMode.Create, FileAccess.Write);
  28. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  29. stream.CopyTo(fileStream);
  30. }
  31. #endregion
  32. /// <summary>
  33. /// 删除文件。
  34. /// </summary>
  35. public static void Delete(string filePath) =>
  36. File.Delete(PathUtils.ToLongPath(filePath));
  37. /// <summary>
  38. /// 确定指定的文件是否存在。
  39. /// </summary>
  40. public static bool Exists(string filePath) =>
  41. File.Exists(PathUtils.ToLongPath(filePath));
  42. /// <summary>
  43. /// 创建 <see cref="FileInfo"/> 对象。
  44. /// </summary>
  45. public static FileInfo GetInfo(string path) =>
  46. new(PathUtils.ToLongPath(path));
  47. /// <summary>
  48. /// 打开该文件的只读 <see cref="FileStream"/>。
  49. /// </summary>
  50. public static FileStream OpenRead(string filePath) =>
  51. new(PathUtils.ToLongPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  52. /// <summary>
  53. /// 在指定路径创建文件,并打开 <see cref="FileStream"/>。
  54. /// </summary>
  55. public static FileStream OpenCreate(string filePath) {
  56. DirectoryUtils.Create(filePath, isFilePath: true);
  57. return new(PathUtils.ToLongPath(filePath), FileMode.Create);
  58. }
  59. }