JsonConfig.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. /// <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. Save();
  46. }
  47. /// <summary>
  48. /// 获取配置信息
  49. /// </summary>
  50. /// <returns></returns>
  51. public T Get()
  52. {
  53. return this.Config;
  54. }
  55. /// <summary>
  56. /// 保存配置信息
  57. /// </summary>
  58. /// <returns></returns>
  59. public bool Save()
  60. {
  61. string s = Json.Object2String(this.Config);
  62. s = JsonFormat.Format(s);
  63. bool result = TxtTool.Create(this.FilePath, s);
  64. if (TxtTool.Create(this.FilePathBackup, s))
  65. {
  66. if (FileTool.Copy(this.FilePathBackup, this.FilePath, true))
  67. {
  68. FileTool.Delete(this.FilePathBackup);
  69. }
  70. }
  71. return result;
  72. }
  73. }
  74. }