FileHelper.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. namespace Admin.NET.Core;
  7. /// <summary>
  8. /// 文件帮助类
  9. /// </summary>
  10. public static class FileHelper
  11. {
  12. /// <summary>
  13. /// 尝试删除文件/目录
  14. /// </summary>
  15. /// <param name="path"></param>
  16. /// <returns></returns>
  17. public static bool TryDelete(string path)
  18. {
  19. try
  20. {
  21. if (string.IsNullOrEmpty(path)) return false;
  22. if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
  23. else File.Delete(path);
  24. return true;
  25. }
  26. catch (Exception)
  27. {
  28. // ignored
  29. return false;
  30. }
  31. }
  32. /// <summary>
  33. /// 复制目录
  34. /// </summary>
  35. /// <param name="sourceDir"></param>
  36. /// <param name="destinationDir"></param>
  37. /// <param name="overwrite"></param>
  38. public static void CopyDirectory(string sourceDir, string destinationDir, bool overwrite = false)
  39. {
  40. // 检查源目录是否存在
  41. if (!Directory.Exists(sourceDir)) throw new DirectoryNotFoundException("Source directory not found: " + sourceDir);
  42. // 如果目标目录不存在,则创建它
  43. if (!Directory.Exists(destinationDir)) Directory.CreateDirectory(destinationDir!);
  44. // 获取源目录下的所有文件并复制它们
  45. foreach (string file in Directory.GetFiles(sourceDir))
  46. {
  47. string name = Path.GetFileName(file);
  48. string dest = Path.Combine(destinationDir, name);
  49. File.Copy(file, dest, overwrite);
  50. }
  51. // 递归复制所有子目录
  52. foreach (string directory in Directory.GetDirectories(sourceDir))
  53. {
  54. string name = Path.GetFileName(directory);
  55. string dest = Path.Combine(destinationDir, name);
  56. CopyDirectory(directory, dest, overwrite);
  57. }
  58. }
  59. /// <summary>
  60. /// 在文件倒数第lastIndex个identifier前插入内容(备份原文件)
  61. /// </summary>
  62. /// <param name="filePath">文件路径</param>
  63. /// <param name="insertContent">要插入的内容</param>
  64. /// <param name="identifier">标识符号</param>
  65. /// <param name="lastIndex">倒数第几个标识符</param>
  66. /// <param name="createBackup">是否创建备份文件</param>
  67. public static async Task InsertsStringAtSpecifiedLocationInFile(string filePath, string insertContent, char identifier, int lastIndex, bool createBackup = false)
  68. {
  69. // 参数校验
  70. if (lastIndex < 1) throw new ArgumentOutOfRangeException(nameof(lastIndex));
  71. if (identifier == 0) throw new ArgumentException("标识符不能为空字符");
  72. if (!File.Exists(filePath))
  73. throw new FileNotFoundException("目标文件不存在", filePath);
  74. // 创建备份文件
  75. if (createBackup)
  76. {
  77. string backupPath = $"{filePath}.bak_{DateTime.Now:yyyyMMddHHmmss}";
  78. File.Copy(filePath, backupPath, true);
  79. }
  80. using var reader = new StreamReader(filePath, Encoding.UTF8);
  81. var content = await reader.ReadToEndAsync();
  82. reader.Close();
  83. // 逆向查找算法
  84. int index = content.LastIndexOf(identifier);
  85. if (index == -1)
  86. {
  87. throw new ArgumentException($"文件中未包含{identifier}");
  88. }
  89. int resIndex = content.LastIndexOf(identifier, index - lastIndex);
  90. if (resIndex == -1)
  91. {
  92. throw new ArgumentException($"文件中{identifier}不足{lastIndex}个");
  93. }
  94. StringBuilder sb = new StringBuilder(content);
  95. sb = sb.Insert(resIndex, insertContent);
  96. await WriteToFileAsync(filePath, sb);
  97. }
  98. /// <summary>
  99. /// 写入文件内容
  100. /// </summary>
  101. /// <param name="filePath"></param>
  102. /// <param name="sb"></param>
  103. public static async Task WriteToFileAsync(string filePath, StringBuilder sb)
  104. {
  105. Console.ForegroundColor = ConsoleColor.DarkGreen;
  106. await using var writer = new StreamWriter(filePath, false, new UTF8Encoding(false)); // 无BOM
  107. await writer.WriteAsync(sb.ToString());
  108. writer.Close();
  109. Console.WriteLine($"文件【{filePath}】写入完成");
  110. Console.ResetColor();
  111. }
  112. }