JsonAppConfig.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using Azylee.Core.AppUtils.AppConfigUtils;
  2. using Azylee.Core.AppUtils.AppConfigUtils.AppConfigInterfaces;
  3. using Azylee.Core.AppUtils.AppConfigUtils.AppConfigModels;
  4. using Azylee.Core.DataUtils.DateTimeUtils;
  5. using Azylee.Core.IOUtils.FileUtils;
  6. using Azylee.Core.IOUtils.TxtUtils;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. namespace Azylee.Jsons.JsonAppConfigUtils
  13. {
  14. /// <summary>
  15. /// Json 配置管理器
  16. ///
  17. /// 如何使用:
  18. /// 1. 根据自己需求,创建配置类,实现IAppConfigModel接口
  19. /// 2. 使用配置管理器,new出创建的配置类
  20. /// 3. 通过配置管理器,管理配置信息即可
  21. /// PS. 建议直接使用静态变量创建
  22. /// </summary>
  23. /// <typeparam name="T"></typeparam>
  24. public class JsonAppConfig<T> : AppConfig<T> where T : IAppConfigModel, new()
  25. {
  26. private string FilePath;
  27. private string FilePathBackup;
  28. private JsonAppConfig() { }
  29. /// <summary>
  30. /// 构造配置管理器
  31. /// </summary>
  32. /// <param name="filepath">配置文件路径</param>
  33. public JsonAppConfig(string filepath)
  34. {
  35. this.FilePath = filepath;
  36. this.FilePathBackup = filepath + ".backup";
  37. // 配置初始化
  38. OnCreate();
  39. // 重置配置项
  40. this.Config.ForceSet();
  41. // 保存配置
  42. DoSave();
  43. }
  44. public override bool OnCreate()
  45. {
  46. // 读取默认配置文件
  47. if (File.Exists(this.FilePath))
  48. {
  49. this.Config = Json.File2Object<T>(this.FilePath);
  50. }
  51. // 读取备份的配置文件
  52. if (this.Config == null)
  53. {
  54. if (File.Exists(this.FilePathBackup))
  55. {
  56. this.Config = Json.File2Object<T>(this.FilePathBackup);
  57. }
  58. }
  59. if (this.Config == null)
  60. {
  61. // 配置读取为空,有可能是配置内容发生结构性改变,JSON解析失败
  62. // 所以,此处对原配置文件先进行备份,防止内容丢失
  63. FileTool.Copy(this.FilePath, this.FilePath + ".backup" + "." + DateTimeFormatter.Compact(DateTime.Now), true);
  64. this.Config = new T();
  65. }
  66. return true;
  67. }
  68. public override bool OnDestroy()
  69. {
  70. return DoSave();
  71. }
  72. /// <summary>
  73. /// 保存配置信息
  74. /// </summary>
  75. /// <returns></returns>
  76. public override bool DoSave()
  77. {
  78. string s = Json.Object2String(this.Config);
  79. s = JsonFormat.Format(s);
  80. TxtTool.Create(this.FilePath, s);
  81. bool result = TxtTool.Create(this.FilePathBackup, s);
  82. if (result)
  83. {
  84. if (Json.File2Object<T>(this.FilePathBackup) != null)
  85. {
  86. if (FileTool.Copy(this.FilePathBackup, this.FilePath, true))
  87. {
  88. FileTool.Delete(this.FilePathBackup);
  89. }
  90. }
  91. }
  92. return result;
  93. }
  94. }
  95. }