手动读取配置文件appsettings.json
在代码中手动读取配置文件 :
//在代码中手动读取配置文件 public class ReadConfig { /// <summary> /// 读取配置文件,默认读:appsettings.json /// </summary> /// <param name="nodeName">节点,多层节(ConnectionStrings:RedisConnection)</param> /// <param name="configFileName">配置文件名,默认:appsettings.json</param> /// <returns></returns> public static string Read(string nodeName, string? configFileName = "appsettings.json") { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configFileName = string.IsNullOrEmpty(configFileName) ? "appsettings.json" : configFileName; configFileName = configFileName.Contains(".json") ? configFileName : $"{configFileName}.json"; configBuilder.AddJsonFile(configFileName.Trim(), optional: false, reloadOnChange: true); IConfiguration config = configBuilder.Build(); string value = config[nodeName.Trim()]; return value; } }
依赖开发包:Microsoft.Extensions.Configuration,Microsoft.Extensions.Configuration.Json