using IMCS.CCS.Common; using IMCS.CCS.Common.Redis; using Microsoft.AspNetCore.Hosting; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace IMCS.CCS.Service.Impl { /// /// 数据服务 /// public class DataService : IDataService { private readonly string _webRootPath; private string PathOrKey { get; set; } private readonly IDataStorageConfigurationService _dataStorageConfigurationService; private readonly IRedisService _redisService; public DataService(IWebHostEnvironment webHostEnvironment, IDataStorageConfigurationService dataStorageConfigurationService, IRedisService redisService) { _webRootPath = webHostEnvironment.WebRootPath; _dataStorageConfigurationService = dataStorageConfigurationService; _redisService = redisService; } public bool Init(string pathOrKey) { PathOrKey = pathOrKey; return true; } /// /// 读取数据 /// /// /// public async Task> ReadDataAsync() { var data = string.Empty; if (_dataStorageConfigurationService.IsUseRedis()) { data = await this._redisService.Database.StringGetAsync(PathOrKey); } else { try { var path = this.GetPath(); //using var fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); //var buffer = new byte[fs.Length]; //fs.Position = 0; //await fs.ReadAsync(buffer, 0, buffer.Length); //var data = Encoding.UTF8.GetString(buffer); //if (string.IsNullOrWhiteSpace(data)) return default; data = await File.ReadAllTextAsync(path); } catch (Exception ex) { Console.WriteLine("读取文件失败====》" + ex.Message); //return await ReadDataAsync(); } } return string.IsNullOrWhiteSpace(data) ? default : JsonConvert.DeserializeObject>(data); } /// /// 写入数据 /// /// public async Task WriteDataAsync(T contents) { var json = JsonConvert.SerializeObject(contents); if (_dataStorageConfigurationService.IsUseRedis()) { await this._redisService.Database.StringSetAsync(PathOrKey, json); } else { try { var path = this.GetPath(); //using var fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); //fs.Seek(0, SeekOrigin.Begin); //fs.SetLength(0); //var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(contents)); //fs.Position = 0; //await fs.WriteAsync(data, 0, data.Length); await File.WriteAllTextAsync(path, json); } catch (Exception ex) { Console.WriteLine("更新JSON文件失败==>"+ex.Message); //return await WriteDataAsync(contents); } } return true; } #region 私有 private string GetPath() { if (string.IsNullOrWhiteSpace(PathOrKey)) throw new MessageBox("属性 FilePath 空对象,请使用前调用 Init 函数!"); var path = _webRootPath + PathOrKey; if (!File.Exists(path)) { File.Create(path); } return path; } #endregion } }