1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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
- {
- /// <summary>
- /// 文件数据服务
- /// </summary>
- 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;
- }
- /// <summary>
- /// 读取文件
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns></returns>
- public async Task<IEnumerable<T>> ReadDataAsync<T>()
- {
- var path = this.GetPath();
- var data = await File.ReadAllTextAsync(path);
- if (string.IsNullOrWhiteSpace(data)) return default;
- return JsonConvert.DeserializeObject<IEnumerable<T>>(data);
- }
- /// <summary>
- /// 写入数据
- /// </summary>
- /// <returns></returns>
- public async Task<bool> WriteDataAsync<T>(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
- }
- }
|