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

⒈添加依赖

  Microsoft.Extensions.Configuration

  Microsoft.Extensions.Configuration.FileExtensions

  Microsoft.Extensions.Configuration.Json

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

1 {
2   "ConnectionStrings": {
3     "StudyConnStr": "Data Source=.;Initial Catalog=Study;User ID=sa;Password=admin"
4   }
5 }

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

 1 using Microsoft.Extensions.Configuration;
 2 using System;
 3 using System.IO;
 4 
 5 namespace Config_Test
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             var build = new ConfigurationBuilder();
12             build.SetBasePath(Directory.GetCurrentDirectory());
13             build.AddJsonFile("//Config//dbconfig.json", true, true);
14             var dbConfig = build.Build();
15             string dbConn = dbConfig.GetSection("ConnectionStrings").GetSection("StudyConnStr").Value;
16             Console.WriteLine($"db连接字符串:{dbConfig["ConnectionStrings:StudyConnStr"]}");
17             Console.WriteLine($"db连接字符串:{dbConn}");
18             Console.ReadKey();
19         }
20     }
21 }

 

posted @ 2019-05-03 21:55  SpringCore  阅读(2715)  评论(0编辑  收藏  举报