.Net Core控制台应用加载读取Json配置文件

⒈添加依赖

  Microsoft.Extensions.Configuration

  Microsoft.Extensions.Configuration.FileExtensions

  Microsoft.Extensions.Configuration.Json

⒉在项目中添加Json配置文件并将其复制到输出目录属性设置为“始终复制”

 {
"ConnectionStrings": {
"StudyConnStr": "Data Source=.;Initial Catalog=Study;User ID=sa;Password=admin"
}
}

.Net Core控制台应用加载读取Json配置文件

⒊在代码中加载配置文件并读取相应内容

 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();
}
}
}
上一篇:golang.org/x/crypto/ssh使用


下一篇:C#利用newtonsoft.json读取.so配置文件内容