背景
目前发现网上的 .NET Core 读取 json 格式的配置文件有点麻烦,自己想搞个简单点的。
.NET Core 目前的主流形式是采用 json 格式来存储配置文件信息,跟之前的诸如 app.config 和 web.config 等 xml 形式的配置文件有所区别。
json 文件 demo
appsettings.json:
{ "name": "wen", "age": 26, "family": { "mother": { "name": "娘", "age": 55 }, "father": { "name": "爹", "age": 56 } } }
Nuget 类库引用
需要 Nuget 两个类库:
①Microsoft.Extensions.Configuration
②Microsoft.Extensions.Configuration.Json
核心代码:
Program.cs:
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(); } } }
测试结果:
直观的关系对比图,可以看到核心就是 GetSection() 方法,每继续往下一个层次获取就再次调用 GetSection() 方法:
备注
别忘了设置 json 文件的属性哦:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持站长技术。
清明节在 CSDN 博客社区用自己的方式致敬两位逝去的博主。 雷神 雷霄骅 他 CSDN ...
什么是操作系统 操作系统由 内核和应用 组成在计算机软硬件架构中操作系统起到的...
以下是代码片段: '*********************************************************...
在我们浏览不同网页的时候,我们可以通过浏览器的前进、后退键来去到我们前后访...
MySQL数据是如何存储的? 聚集索引 我们先建如下的一张表 CREATE TABLE `student`...
我自己做了一个小程序大家可以试试 程序里面带有密码密码是 3345615469 c语言总...
文章目录 1.进程间通信 1.1 进程间通讯概述 1.2 进程间通信目的 1.3 进程间通信...
3月4日消息 外媒 Windows Latest 报道,在未来几周或几个月内,微软表示将开始在...
一般来说浏览器要同时下载几个文件,比如pdf文件,会在服务器端把几个文件压缩成...
如果你依然使用 Windows 10 Version 1909/1903 甚至更老的系统,那么你可能已经...