1. 控制台应用
新建一个控制台应用,添加两个Package:
Install-Package Microsoft.Extensions.Configuration Install-Package Microsoft.Extensions.Configuration.Json
创建配置文件appsettings.json:
{ "Data": "10000", "ConnectionStrings": { "DevContext": "开发库", "ProdContext": "生产库" } }
读取配置文件:
using System; using System.IO; using Microsoft.Extensions.Configuration; namespace Libing.Core.ConsoleApp { class Program { static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var config = builder.Build(); Console.WriteLine(config["Data"]); Console.WriteLine(config.GetSection("ConnectionStrings:DevContext").Value); } } }
通过ConfigurationBuilder对象来创建ConfigurationRoot对象,进行读取配置文件。
SetBasePath:设置配置文件基础路径
AddJsonFile:添加读取的Json文件
原文地址:https://www.cnblogs.com/libingql/p/11326358.html
时间: 2024-11-08 01:22:19