using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using System; using System.Configuration; using System.Threading; namespace WpfLiBroker { public class AppConfig { public static Microsoft.Extensions.Configuration.IConfiguration config { get; private set; } private static DateTime last_changed_time = DateTime.MinValue; static AppConfig() { config = new ConfigurationBuilder() .SetBasePath(System.Environment.CurrentDirectory) .AddJsonFile("config.json", false, true) .Build(); LoadData(); //测试此处可以不加 这里加上以防万一 ChangeToken.OnChange(() => { var span = DateTime.Now - last_changed_time; last_changed_time = DateTime.Now; if (span < TimeSpan.FromSeconds(1)){ System.Diagnostics.Debug.WriteLine($"{DateTime.Now.ToLongTimeString()} config change do nothing!"); return config.GetReloadToken(); } else { System.Diagnostics.Debug.WriteLine($"{DateTime.Now.ToLongTimeString()} config change do something!"); //********************************** LoadData(); //####################################### var data = config.GetReloadToken(); return data; } } , ()=> { });// () => autoReset.Set() } private static void LoadData() { Account = config.GetSection("account").Get<Account>(); } public static Account Account { get; private set; } } public class Account { public string login_code { get; set; } public string login_pwd { get; set; } } }
配置文件:config.json
{ "account": { "login_code": "code", "login_pwd": "pwd" } }
主要实现了配置文件修改后 程序绑定的变量自动刷新