You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

53 lines
1.3 KiB

  1. using Newtonsoft.Json;
  2. using System;
  3. using System.IO;
  4. using System.Collections.Concurrent;
  5. namespace HBLConsole.Service
  6. {
  7. /// <summary>
  8. /// Json参数服务类
  9. /// </summary>
  10. public class Json<T> where T : class, new()
  11. {
  12. private volatile static Json<T> _Instance;
  13. public static Json<T> GetInstance => _Instance ?? (_Instance = new Json<T>());
  14. private Json() { }
  15. static string path
  16. {
  17. get
  18. {
  19. Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AccessFile"));
  20. return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\{typeof(T).Name}.json";
  21. }
  22. }
  23. public T Base { get; set; } = new T();
  24. /// <summary>
  25. /// 保存数据
  26. /// </summary>
  27. public void Save()
  28. {
  29. string outjson = JsonConvert.SerializeObject(Base);
  30. File.WriteAllText(path, outjson);
  31. }
  32. /// <summary>
  33. /// 获取保存的数据
  34. /// </summary>
  35. public void Read()
  36. {
  37. if (File.Exists(path))
  38. {
  39. string JsonString = File.ReadAllText(path);
  40. var result = JsonConvert.DeserializeObject<T>(JsonString);
  41. if (result != null) { Base = result; }
  42. }
  43. }
  44. }
  45. }