前言,好记性不如烂笔头
1,NuGet管理器添加 三个引用:
Microsoft.Extensions.Configuration,
Microsoft.Extensions.Configuration.Binder,
Microsoft.Extensions.Configuration.Json
2,添加一个工具类ConfigUtils
public class ConfigUtils {
private ConfigurationBuilder _builder;
private IConfigurationRoot _configuration;
/// <summary>
/// 构造函数初始化配置文件
/// </summary>
/// <param name="jsonFile"></param>
public ConfigUtils(string jsonFile) {
_builder = new ConfigurationBuilder();
_builder.AddJsonFile(jsonFile, optional: false, reloadOnChange: true);
}
/// <summary>
/// 读取配置文件节点
/// </summary>
/// <returns></returns>
public IConfigurationRoot GetConfigurationRoot() {
if (_configuration == null)
_configuration = _builder.Build();
return _configuration;
}
}
3,按照配置文件构造对应节点json对象类,读取该节点数据的时候,就传入具体配置文件名称和节点名称
/// <summary>
/// 泛型读取配置文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonFile"></param>
/// <param name="key"></param>
/// <returns></returns>
public static T GetConfig<T>(string jsonFile, string key) where T : new() {
ConfigUtils utils = new ConfigUtils(jsonFile);
var root = utils.GetConfigurationRoot();
T config = new T();
root.Bind(key, config);
return config;
}
/// <summary>
/// 节点读取配置文件
/// </summary>
/// <param name="jsonFile"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetConfig(string jsonFile, string key) {
ConfigUtils utils = new ConfigUtils(jsonFile);
var root = utils.GetConfigurationRoot();
return root[key];
}