编程语言
首页 > 编程语言> > vs C#项目读取JSON配置文件

vs C#项目读取JSON配置文件

作者:互联网

config.json 文件内容如下

{
	"Data": 
	{
		"DefaultConnection": 
		{
			"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Books;Trusted_Connection=True;"
		}
	},
	"Appsettings": 
	{
    "Name": "XiaoLi",
    "Date": "2020-04-18",
    "age": "20"
    },
    "url":"https://blog.csdn.net/weixin_42686768"
}

设置配置文件
项目config.json文件右键——属性——将“复制到输出目录”项的值改为“始终复制”

添加引用

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.IO;
public static string GetConnectionString(string value)
{
    var configurationBuilder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("config.json");

    //var configurationBuilder = new ConfigurationBuilder()
    //    .Add(new JsonConfigurationSource { Path = "config.json", ReloadOnChange = true });

    IConfiguration config = configurationBuilder.Build();
    string connectionString = config[value];
    return connectionString;
}

// 1、获取 ConnectionString 对应的字符串
va = "Data:DefaultConnection:ConnectionString";
// 2、获取 Name  对应的字符串
va = "Appsettings:Name";
// 3、获取 url 对应的字符串
va = "url";

GetConnectionString(va)

标签:va,configurationBuilder,Name,配置文件,C#,ConnectionString,json,JSON,config
来源: https://blog.csdn.net/weixin_42686768/article/details/105595689