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

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

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

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课:文件配置提供程序)--学习笔记


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

查看所有标签

猜你喜欢:

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

Hacking

Hacking

Jon Erickson / No Starch Press / 2008-2-4 / USD 49.95

While other books merely show how to run existing exploits, Hacking: The Art of Exploitation broke ground as the first book to explain how hacking and software exploits work and how readers could deve......一起来看看 《Hacking》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码