JsonAppConfig.cs 2.5 KB

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