⒈添加依賴
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 }