⒈添加依赖
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
⒉在项目中添加Json配置文件并将其复制到输出目录属性设置为“始终复制”
{
"ConnectionStrings": {
"StudyConnStr": "Data Source=.;Initial Catalog=Study;User ID=sa;Password=admin"
}
}
⒊在代码中加载配置文件并读取相应内容
using Microsoft.Extensions.Configuration;
using System;
using System.IO; namespace Config_Test
{
class Program
{
static void Main(string[] args)
{
var build = new ConfigurationBuilder();
build.SetBasePath(Directory.GetCurrentDirectory());
build.AddJsonFile("//Config//dbconfig.json", true, true);
var dbConfig = build.Build();
string dbConn = dbConfig.GetSection("ConnectionStrings").GetSection("StudyConnStr").Value;
Console.WriteLine($"db连接字符串:{dbConfig["ConnectionStrings:StudyConnStr"]}");
Console.WriteLine($"db连接字符串:{dbConn}");
Console.ReadKey();
}
}
}