JsonConfig.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 : IJsonConfigModel, new()
  15. {
  16. private T Config { get; set; }
  17. private string FilePath { get; set; }
  18. private string FilePathBackup { get; set; }
  19. private JsonConfig() { }
  20. /// <summary>
  21. /// 构造配置管理器
  22. /// </summary>
  23. /// <param name="filepath">配置文件路径</param>
  24. public JsonConfig(string filepath)
  25. {
  26. this.FilePath = filepath;
  27. this.FilePathBackup = filepath + ".backup";
  28. // 读取默认配置文件
  29. if (File.Exists(this.FilePath))
  30. {
  31. this.Config = Json.File2Object<T>(this.FilePath);
  32. }
  33. // 读取备份的配置文件
  34. if (this.Config == null)
  35. {
  36. if (File.Exists(this.FilePathBackup))
  37. {
  38. this.Config = Json.File2Object<T>(this.FilePathBackup);
  39. }
  40. }
  41. if (this.Config == null)
  42. {
  43. this.Config = new T();
  44. }
  45. // 重置配置项
  46. this.Config.Reset();
  47. Save();
  48. }
  49. /// <summary>
  50. /// 获取配置信息
  51. /// </summary>
  52. /// <returns></returns>
  53. public T Get()
  54. {
  55. return this.Config;
  56. }
  57. /// <summary>
  58. /// 保存配置信息
  59. /// </summary>
  60. /// <returns></returns>
  61. public bool Save()
  62. {
  63. string s = Json.Object2String(this.Config);
  64. s = JsonFormat.Format(s);
  65. bool result = TxtTool.Create(this.FilePath, s);
  66. if (TxtTool.Create(this.FilePathBackup, s))
  67. {
  68. if (FileTool.Copy(this.FilePathBackup, this.FilePath, true))
  69. {
  70. FileTool.Delete(this.FilePathBackup);
  71. }
  72. }
  73. return result;
  74. }
  75. }
  76. }