FileHelper.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System.IO;
  2. using System.Threading.Tasks;
  3. namespace Team.Utility
  4. {
  5. public static class FileHelper
  6. {
  7. /// <summary>
  8. /// 创建文件
  9. /// </summary>
  10. /// <param name="path">文件路径</param>
  11. /// <param name="str">文件内容</param>
  12. public static void Save(string path, string str)
  13. {
  14. var s = path.Substring(0, path.LastIndexOf('\\'));
  15. Directory.CreateDirectory(s); //如果文件夹不存在就创建它
  16. using var fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
  17. var data = System.Text.Encoding.Default.GetBytes(str);
  18. //开始写入
  19. fs.Write(data, 0, data.Length);
  20. }
  21. /// <summary>
  22. /// 创建文件
  23. /// </summary>
  24. /// <param name="path">文件路径</param>
  25. /// <param name="str">文件内容</param>
  26. public static async Task SaveAsync(string path, string str)
  27. {
  28. var s = path.Substring(0, path.LastIndexOf('\\'));
  29. Directory.CreateDirectory(s);//如果文件夹不存在就创建它
  30. using var fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
  31. var data = System.Text.Encoding.UTF8.GetBytes(str);
  32. //开始写入
  33. await fs.WriteAsync(data, 0, data.Length);
  34. }
  35. }
  36. }