添加NuGet包
Microsoft.Extensions.Configuration.FileExtensions;
Microsoft.Extensions.Configuration.Json;
appsettings.json示例
代码:
public static void GetBuilder(string path) { var builder = new ConfigurationBuilder() //设置文件放置路径 .SetBasePath(path) //appsettings.json,复制一份放在程序集目录下 .AddJsonFile(appsettings, optional: true, reloadOnChange: true); var configuration = builder.Build(); var connectionStr = configuration.GetConnectionString("Default")!;//数据库默认字符串的独特方式获取 var num = int.Parse(configuration.GetSection("Log:LogLevel").Value!);//方式一,通过":"来表示层级获取数据 var str = configuration.GetSection("Log").GetSection("LogPath").Value!;//方式二,直接通过叠加使用GetSection()来表示层级获取数据
}
完整示例
public static class AppConfigurations
{ private const string appsettings = "appsettings.json"; public static readonly ConcurrentDictionary<string, IConfigurationRoot> ConfigurationCache; public static string ConnectionString { get; set; }
public static string LogPath{ get; set; } public static int LogLevel{ get; set; } static AppConfigurations() { ConfigurationCache = new ConcurrentDictionary<string, IConfigurationRoot>(); ConnectionString = Get(Directory.GetCurrentDirectory()).GetConnectionString("Default")!;
LogLevel= int.Parse(Get(Directory.GetCurrentDirectory()).GetSection("Log:LogLevel").Value!);
LogPath= Get(Directory.GetCurrentDirectory()).GetSection("Log").GetSection("LogPath").Value!;
} public static IConfigurationRoot Get(string path) { var cacheKey = path; return ConfigurationCache.GetOrAdd( cacheKey, _ => GetBuilder(path) ); } public static IConfigurationRoot GetBuilder(string path) { var builder = new ConfigurationBuilder() //设置文件放置路径 .SetBasePath(path) //appsettings.json,复制一份放在程序集目录下 .AddJsonFile(appsettings, optional: true, reloadOnChange: true); return builder.Build(); } }
标签:GetSection,配置文件,C#,appsettings,json,static,var,public From: https://www.cnblogs.com/sugarwxx/p/17605542.html