FileDataService.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using IMCS.CCS.Common;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. namespace IMCS.CCS.Service.Impl
  10. {
  11. /// <summary>
  12. /// 文件数据服务
  13. /// </summary>
  14. public class FileDataService : IFileDataService
  15. {
  16. private readonly string _webRootPath;
  17. private string FilePath { get; set; }
  18. public FileDataService(IWebHostEnvironment webHostEnvironment)
  19. {
  20. _webRootPath = webHostEnvironment.WebRootPath;
  21. }
  22. public bool Init(string path)
  23. {
  24. FilePath = path;
  25. return true;
  26. }
  27. /// <summary>
  28. /// 读取文件
  29. /// </summary>
  30. /// <typeparam name="T"></typeparam>
  31. /// <returns></returns>
  32. public async Task<IEnumerable<T>> ReadDataAsync<T>()
  33. {
  34. var path = this.GetPath();
  35. var data = await File.ReadAllTextAsync(path);
  36. if (string.IsNullOrWhiteSpace(data)) return default;
  37. return JsonConvert.DeserializeObject<IEnumerable<T>>(data);
  38. }
  39. /// <summary>
  40. /// 写入数据
  41. /// </summary>
  42. /// <returns></returns>
  43. public async Task<bool> WriteDataAsync<T>(T contents)
  44. {
  45. var path = this.GetPath();
  46. await File.WriteAllTextAsync(path, JsonConvert.SerializeObject(contents));
  47. return true;
  48. }
  49. #region 私有
  50. private string GetPath()
  51. {
  52. if (string.IsNullOrWhiteSpace(FilePath)) throw new MessageBox("属性 FilePath 空对象,请使用前调用 Init 函数!");
  53. var path = _webRootPath + FilePath;
  54. if (!File.Exists(path))
  55. {
  56. File.Create(path);
  57. }
  58. return path;
  59. }
  60. #endregion
  61. }
  62. }