Nuget 类库引用
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
json 文件 demo
{
"name": "wen",
"age": 26,
"family": {
"mother": {
"name": "娘",
"age": 55
},
"father": {
"name": "爹",
"age": 56
}
}
}
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
//添加 json 文件路径
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
//创建配置根对象
var configurationRoot = builder.Build();
//取配置根下的 name 部分
var nameSection = configurationRoot.GetSection("name");
//取配置根下的 family 部分
var familySection = configurationRoot.GetSection("family");
//取 family 部分下的 mother 部分下的 name 部分
var motherNameSection = familySection.GetSection("mother").GetSection("name");
//取 family 部分下的 father 部分下的 age 部分
var fatherAgeSection = familySection.GetSection("father").GetSection("age");
//Value 为文本值
Console.WriteLine($"name: {nameSection.Value}");
Console.WriteLine($"motherName: {motherNameSection.Value}");
Console.WriteLine($"fatherAge: {fatherAgeSection.Value}");
Console.Read();
}
}
}
评论 (0)