You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
3.0 KiB

4 years ago
4 years ago
4 years ago
  1. using Apewer;
  2. using Apewer.Internals;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. namespace Apewer
  7. {
  8. /// <summary></summary>
  9. public class Configuration
  10. {
  11. private static Json _json = null;
  12. private static bool _loaded = false;
  13. private static Json JsonFile
  14. {
  15. get
  16. {
  17. if (!_loaded) Load();
  18. return _json ?? Json.NewObject();
  19. }
  20. }
  21. private static string GetPath()
  22. {
  23. if (StorageUtility.FileExists("config.json"))
  24. {
  25. return "config.json";
  26. }
  27. if (StorageUtility.FileExists("configuration.json"))
  28. {
  29. return "configuration.json";
  30. }
  31. try
  32. {
  33. var type = typeof(Configuration);
  34. var path = System.IO.Path.GetDirectoryName(type.Assembly.CodeBase);
  35. if (path.StartsWith("file:\\") && path.Length > 6) path = path.Substring(6);
  36. var ad_config = path + "\\..\\app_data\\config.json";
  37. if (StorageUtility.FileExists(ad_config)) return ad_config;
  38. var ad_configuration = path + "\\..\\app_data\\configuration.json";
  39. if (StorageUtility.FileExists(ad_configuration)) return ad_configuration;
  40. var wr_config = path + "\\..\\config.json";
  41. if (StorageUtility.FileExists(ad_config)) return wr_config;
  42. var wr_configuration = path + "\\..\\configuration.json";
  43. if (StorageUtility.FileExists(ad_configuration)) return ad_configuration;
  44. }
  45. catch { }
  46. return null;
  47. }
  48. /// <summary>从默认路径加载配置文件,默认文件名为 config.json 和 configuration.json。</summary>
  49. public static bool Load()
  50. {
  51. var path = GetPath();
  52. if (path != null && StorageUtility.FileExists(path))
  53. {
  54. var text = TextUtility.FromBytes(StorageUtility.ReadFile(path, true));
  55. var loaded = Load(text);
  56. if (loaded) return true;
  57. }
  58. return false;
  59. }
  60. /// <summary>加载配置文件。</summary>
  61. public static bool Load(string json)
  62. {
  63. var text = json;
  64. _json = Json.From(text);
  65. return _json != null;
  66. }
  67. /// <summary>获取配置文件中的属性。</summary>
  68. public static Json GetProperties(Type type)
  69. {
  70. if (type == null) return null;
  71. var result = GetProperties((string)type.FullName);
  72. return result;
  73. }
  74. /// <summary>获取配置文件中的属性。</summary>
  75. public static Json GetProperties(string type)
  76. {
  77. if (TextUtility.IsBlank(type)) return null;
  78. var config = JsonFile;
  79. if (config == null) return null;
  80. return config.GetProperty(type);
  81. }
  82. }
  83. }