JsonAppConfig.cs 2.9 KB

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