前言,好記性不如爛筆頭
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];
}