public ConfigManager(string filePath) { //文件存在则加载,否则创建 if (File.Exists(filePath)) { Reload(filePath); } else { _filePath = filePath; _config = new MagnesiumConfig(); Save(); } _config.ConfigChanged += (sender, e) => Save(); }
/// <summary> /// 重新从指定路径加载配置文件 /// </summary> /// <param name="filePath"></param> public void Reload(string filePath) { if (filePath.IsNullOrWhiteSpace()) { throw new ArgumentNullException(nameof(filePath)); } if (File.Exists(filePath) && File.GetAttributes(filePath).HasFlag(FileAttributes.Directory)) { throw new ArgumentException("提供的path为目录,path必须为配置文件"); } _filePath = filePath; using (TextReader sr = File.OpenText(filePath)) { var serializer = new JsonSerializer(); _config = (MagnesiumConfig)serializer.Deserialize(sr, typeof(MagnesiumConfig)); } }
/// <summary> /// 从指定路径加载配置文件 /// </summary> /// <param name="path">配置文件路径</param> public void LoadConfig(string path = "config.json") { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(nameof(path)); } if (File.Exists(path) && File.GetAttributes(path).HasFlag(FileAttributes.Directory)) { throw new ArgumentException("提供的path为目录,path必须为配置文件"); } //加载配置文件 _configManager = new ConfigManager(path); _config = _configManager.Config; UpdateConfig(); //配置对象发生变化时更新配置项 _config.ConfigChanged += (sender, e) => UpdateConfig(); }