亲宝软件园·资讯

展开

C#读取JSON配置文件 vs 中C#项目读取JSON配置文件的方法

z178443085 人气:6

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)

加载全部内容

相关教程
猜你喜欢
用户评论