⒈添加依赖
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 }
原文地址:https://www.cnblogs.com/fanqisoft/p/10806799.html
时间: 2024-10-12 13:28:02