C# 读取json配置文件appsettings.json

添加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();
        }

    }

 注:运行时始终读不到配置抛出异常

 原因是:配置文件没有复制成功到程序集目录下,没有成功的原因是配置文件的属性"复制到输出目录"值是不复制,此属性的值应改为,始终复制或者如果较新则复制,此处选择的是如果较新则复制(源文件有更新则重新复制)

 

posted @ 2023-08-04 12:00  流年sugar  阅读(1917)  评论(0编辑  收藏  举报