摘要:本文主要向大家介绍了C#编程之.Net Core 读取Json配置文件,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
本文主要向大家介绍了C#编程之.Net Core 读取Json配置文件,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
初学.Net Core,很多细节还不熟悉,打算一步一步来学,能学多少就看时间有多少,时间就像海绵里的水,挤一挤总还是有的嘛。
.Net Core读取配置文件相较于以往的方式还是有很大的不同,以往的方式大多要引用System.Configuration 这个类库,且内容要写在app.setting配置文件中才可操作,然后使用底层提供的方法.getConfiguration || .getAppsetting来得到我们需要的数据。
.NetCore读取文件就有了很大的不同,其中变化明显的就是,文件使用Json格式保存,可以自定义名称和内部结构,读取也相当方便,使用层级结构的方式一步一步读取。
一般读取配置文件的方式不做演示,可自行百度,主要通过俩种方式对读取方式进行说明
第一步
首先新建一个.netcore 控制台应用
image.png
第二步
安装 Microsoft.AspNetCore 组件
Install-Package Microsoft.AspNetCore
第三步
新建一个.json文件,填写内容并配置属性
image.png
jsconfig1.json内容
{ "name": "zhb", "age": "10"}
第四步
static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddJsonFile("jsconfig1.json"); var configuration = builder.Build(); Console.WriteLine($"name:{configuration["name"]} age:{configuration["age"]}"); Console.Read(); }
通过这种方式,只需要对json文件进行添加,然后就可以通过configuration变量对内容操作,configuration["name"]就代表得到当前json文件key="name" 的值,特别容易理解
与一种方式其他并无太大差别,只是引用了其他的组件库
需要 Nuget 两个类库:
①Microsoft.Extensions.Configuration
②Microsoft.Extensions.Configuration.Json
appsettings.json
{ "name": "wen", "age": 26, "family": { "mother": { "name": "娘", "age": 55 }, "father": { "name": "爹", "age": 56 } } }
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(); }
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号