博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.net core 基础之读取配置文件

Posted on 2023-04-26 14:48  火冰·瓶  阅读(205)  评论(0)    收藏  举报

一、通过nuget安装扩展包

需要安装如下扩展包

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.Json

 二、在启动项目中新建json文件

{
  "Name": "Alan.hsiang",
  "Age": 20,
  "Sex": "male",
  "Like": [ "basketball", "football", "swimming" ],
  "Score": {
    "LandLit": 90,
    "Mathematics": 99,
    "English": 50
  }
}

三、创建IConfiguration接口实例,通过索引器读取配置文件

//IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("tsconfig.json").Build();  //可以指定路径
IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("tsconfig.json",true,true).Build();
var name = configuration["Name"]; //IConfiguration接口自带的索引器,只返回字符串类型。如:名字
var like0 = configuration["Like:0"];//读取数组中第一个元素 如:第一个爱好
var like2 = configuration["Like:2"];//读取数组中第三个元素 如:第三个爱好
var landLit = configuration["Score:LandLit"];//获取字节点的属性值,如:语文成绩

 四、整体对象绑定

新建一个cs类文件,然后复制整个Json文件的内容,依次点击【编辑-->选择性粘贴-->将JSON粘贴为类】菜单

 默认生成的类名为RootObject,然后修改为Student,具体如下所示:

namespace TestProjectTools
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
        public string[] Like { get; set; }
        public Score Score { get; set; }
    }

    public class Score
    {
        public int LandLit { get; set; }
        public int Mathematics { get; set; }
        public int English { get; set; }
    }
}

将Student类和配置对象进行绑定,如下所示:

//2. 复杂读取
var student = new Student();
configuration.Bind(student);
Console.WriteLine($"name={student.Name},age={student.Age},like= {string.Join(",", student.Like)},score={student.Score.English}");