JsonConfig.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Azylee.Core.IOUtils.FileUtils;
  2. using Azylee.Core.IOUtils.TxtUtils;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. namespace Azylee.Jsons.JsonConfigUtils
  9. {
  10. /// <summary>
  11. /// Json 配置管理器
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. public class JsonConfig<T> where T : new()
  15. {
  16. private T Config { get; set; }
  17. private string FilePath { get; set; }
  18. private string FilePathBackup { get; set; }
  19. private JsonConfig() { }
  20. public JsonConfig(string filepath)
  21. {
  22. this.FilePath = filepath;
  23. this.FilePathBackup = filepath + ".backup";
  24. // 读取默认配置文件
  25. if (File.Exists(this.FilePath))
  26. {
  27. this.Config = Json.File2Object<T>(this.FilePath);
  28. }
  29. // 读取备份的配置文件
  30. if (this.Config == null)
  31. {
  32. if (File.Exists(this.FilePathBackup))
  33. {
  34. this.Config = Json.File2Object<T>(this.FilePathBackup);
  35. }
  36. }
  37. if (this.Config == null)
  38. {
  39. this.Config = new T();
  40. }
  41. Save();
  42. }
  43. public T Get()
  44. {
  45. return this.Config;
  46. }
  47. public bool Save()
  48. {
  49. string s = Json.Object2String(this.Config);
  50. bool result = TxtTool.Create(this.FilePath, s);
  51. if (TxtTool.Create(this.FilePathBackup, s))
  52. {
  53. if (FileTool.Copy(this.FilePathBackup, this.FilePath, true))
  54. {
  55. FileTool.Delete(this.FilePathBackup);
  56. }
  57. }
  58. return result;
  59. }
  60. }
  61. }