using IMCS.CCS.Common; using Microsoft.AspNetCore.Hosting; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace IMCS.CCS.Service.Impl { /// /// 文件数据服务 /// public class FileDataService : IFileDataService { private readonly string _webRootPath; private string FilePath { get; set; } public FileDataService(IWebHostEnvironment webHostEnvironment) { _webRootPath = webHostEnvironment.WebRootPath; } public bool Init(string path) { FilePath = path; return true; } /// /// 读取文件 /// /// /// public async Task> ReadDataAsync() { var path = this.GetPath(); var data = await File.ReadAllTextAsync(path); if (string.IsNullOrWhiteSpace(data)) return default; return JsonConvert.DeserializeObject>(data); } /// /// 写入数据 /// /// public async Task WriteDataAsync(T contents) { var path = this.GetPath(); await File.WriteAllTextAsync(path, JsonConvert.SerializeObject(contents)); return true; } #region 私有 private string GetPath() { if (string.IsNullOrWhiteSpace(FilePath)) throw new MessageBox("属性 FilePath 空对象,请使用前调用 Init 函数!"); var path = _webRootPath + FilePath; if (!File.Exists(path)) { File.Create(path); } return path; } #endregion } }