.NET Core开发实战(第11课:文件配置提供程序)--学习笔记

栏目: IT技术 · 发布时间: 4年前

内容简介:文件配置提供程序这些都是读取不同文件的格式,或者从不同的位置来读取文件文件提供程序支持

11 | 文件配置提供程序:自由选择配置的格式

文件配置提供程序

  • Microsoft.Extensions.Configuration.Ini

  • Microsoft.Extensions.Configuration.Json

  • Microsoft.Extensions.Configuration.NewtonsoftJson

  • Microsoft.Extensions.Configuration.Xml

  • Microsoft.Extensions.Configuration.UserSecrets

这些都是读取不同文件的格式,或者从不同的位置来读取文件

文件提供程序支持

  • 文件是否可选

  • 监视文件的变更

下面通过代码来了解这些特性

源码链接:

https://github.com/witskeeper/geektime/tree/master/samples/ConfigurationFileDemo

引用以下四个包:

  • Microsoft.Extensions.Configuration

  • Microsoft.Extensions.Configuration.Abstractions

  • Microsoft.Extensions.Configuration.Ini

  • Microsoft.Extensions.Configuration.Json

读取 appsettings.json

{
  "Key1": "Value1",
  "Key2": "Value2"
}

主程序

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json");
var configurationRoot = builder.Build();

Console.WriteLine($"Key1:{configurationRoot["Key1"]}");
Console.WriteLine($"Key2:{configurationRoot["Key2"]}");
Console.WriteLine($"Key3:{configurationRoot["Key3"]}");
Console.ReadKey();

启动程序,输出如下:

Key1:Value1
Key2:Value2
Key3:

Key3 不存在,所以他的值是空的

文件是否可选是它的第二个参数 optional,默认情况下是 false

builder.AddJsonFile("appsettings.json", optional:false);

这意味当文件不存在的时候它会报错

它的另一个参数是 reloadOnChange, 默认情况下是 true

builder.AddJsonFile("appsettings.json", optional:false, reloadOnChange:true);

这意味着每次文件变更,它会去读取新文件

接下来看一下 appsettings.ini

Key3=Value3 in ini

主程序

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional:false, reloadOnChange:true);
builder.AddIniFile("appsettings.ini");
var configurationRoot = builder.Build();

Console.WriteLine($"Key1:{configurationRoot["Key1"]}");
Console.WriteLine($"Key2:{configurationRoot["Key2"]}");
Console.WriteLine($"Key3:{configurationRoot["Key3"]}");
Console.ReadKey();

启动程序,输出如下:

Key1:Value1
Key2:Value2
Key3:Value3 in ini

这里可以看到新添加的配置已经生效

builder 中添加配置源是有顺序关系的,后添加的配置会覆盖先添加的配置

.NET Core开发实战(第11课:文件配置提供程序)--学习笔记


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms Sequential & Parallel

Algorithms Sequential & Parallel

Russ Miller、Laurence Boxer / Charles River Media / 2005-08-03 / USD 59.95

With multi-core processors replacing traditional processors and the movement to multiprocessor workstations and servers, parallel computing has moved from a specialty area to the core of computer scie......一起来看看 《Algorithms Sequential & Parallel》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换