读取JSON文件

NuGet两个包:Microsoft.Extensions.Configuration,Mircosoft.Extensions.Configuration.Json

{
"name": "yjw",
"age": 18,
"proxy": {"address": "aa"}
}

需要注意的是,上述json文件,需要设置为”如果较新则复制“,确保在exe同目录下复制该配置文件。

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
string name = configRoot["name"];
var age = configRoot["age"];
Console.WriteLine(name);
string address = configRoot.GetSection("proxy:address").Value;
Console.WriteLine(address);

output:

yjw
aa

除了以上的操作,还可以帮定一个类,自动完成配置的读取,NuGet安装:Microsoft.Extensions.Configuration.Binder

{
"name": "yjw",
"age": 18,
"proxy": {"address": "aa","port": "80"}
}

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text; namespace DITest
{
internal class Program1
{
static void Main()
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
//GetSection返回IConfigurationSection类型,再使用其Get泛型方法,直接可以得到Proxy类
Proxy proxy =configRoot.GetSection("proxy").Get<Proxy>();
Console.WriteLine($"{proxy.address},{proxy.port}");
Console.ReadKey();
}
}
/// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}

output:

aa,80

当然也可以直接用一个类来bind根节点

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text; namespace DITest
{
internal class Program1
{
static void Main()
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
Config config = configRoot.Get<Config>();
Console.WriteLine($"{config.Proxy.address},{config.Proxy.port},{config.Name},{config.Age}");
Console.ReadKey();
}
} class Config
{
public string Name { get; set; }
public string Age { get; set; }
public Proxy Proxy { get; set; }
} /// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}

output:

aa,80,yjw,18

选取方式读取

推荐使用选项方式读取,和DI结合更好,且更好利用”reloadOnChange“机制。

NuGet安装:Microsoft.Extensions.Options,Microsoft.Extensions.Configuration.Binder

读取配置的时候,DI要声明IOptions<T>IOptionsMonitor<T>IOptionsSnapshot<T>等类型。IOptions<T>不会读取到新的值;和IOptionsMonitor相比,IOptionSnapshot<T>会在同一个范围内保持一致,因此,建议使用IOptionSnapshot

Testontrollers.cs:


using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text; namespace DITest
{
internal class TestControllers
{
private readonly IOptionsSnapshot<Config> optConfig;//通过IOptinosSnapshot,将配置类注入 public TestControllers(IOptionsSnapshot<Config> optConfig)//通过IOptinosSnapshot,将配置类注入
{
this.optConfig = optConfig;
}
public void Test()
{
Console.WriteLine(optConfig.Value.Name);//通过optConfig.Value获取Config实例
Console.WriteLine(optConfig.Value.Age);
}
}
}

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text; namespace DITest
{
internal class Program1
{
static void Main()
{
ServiceCollection sc = new ServiceCollection();
sc.AddScoped<TestControllers>();//注册TestControllers
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
sc.AddOptions().Configure<Config>(e=>configRoot.Bind(e));//注册包裹在IOptionSnapshot中的Config
using(var sp = sc.BuildServiceProvider())
{
var c = sp.GetRequiredService<TestControllers>();
c.Test();
}
Console.ReadKey();
}
} class Config
{
public string Name { get; set; }
public string Age { get; set; }
public Proxy Proxy { get; set; }
} /// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}

output:

yjw
18

如果只绑定proxy:

/// <summary>
/// 只读proxy
/// </summary>
class TestControllers2
{
private readonly IOptionsSnapshot<Proxy> optProxy;
public TestControllers2(IOptionsSnapshot<Proxy> optProxy)
{
this.optProxy = optProxy;
}
public void Test()
{
Console.WriteLine(optProxy.Value.address);
Console.WriteLine(optProxy.Value.port);
}
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text; namespace DITest
{
internal class Program1
{
static void Main()
{
ServiceCollection sc = new ServiceCollection();
sc.AddScoped<TestControllers>();//注册TestControllers
sc.AddScoped<TestControllers2>();//注册TestControllers2
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
sc.AddOptions().Configure<Config>(e=>configRoot.Bind(e)).
Configure<Proxy>(e=>configRoot.GetSection("proxy").Bind(e));//绑定proxy
using(var sp = sc.BuildServiceProvider())
{
var c = sp.GetRequiredService<TestControllers2>();
c.Test();
}
Console.ReadKey();
}
} class Config
{
public string Name { get; set; }
public string Age { get; set; }
public Proxy Proxy { get; set; }
} /// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}

output:

aa
80

命令行方式配置

需要NuGet安装Microsoft.Extensions.Configuration.CommandLine

configBuilder.AddCommandLine(args)

参数支持多种格式,比如server=127.0.0.1,--server=127.0.0.1,--server 127.0.0.1/server=127.0.0.1,/server 127.0.0.1

在cmd模式下:xxx.exe name=johnyang age=18

就可以得到该参数.

在VS中,可以在调试属性中,直接写入args

扁平化配置

对于环境变量,命令行等简单的键值对结构,如果想要进行复杂结构的配置,需要进行“扁平化处理”,对于配置的名字需要采用“层级配置”。

比如,json中的

{
"a":{"b":"c"},
"d":{e:[3,5,7]}
}

在cmd中配置为:

a:b:=c d:e:0=3  d:e:1=5  d:e:2=7

C#配置系统的更多相关文章

  1. .NET Core采用的全新配置系统[10]: 配置的同步机制是如何实现的?

    配置的同步涉及到两个方面:第一,对原始的配置文件实施监控并在其发生变化之后从新加载配置:第二,配置重新加载之后及时通知应用程序进而使后者能够使用最新的配置.要了解配置同步机制的实现原理,先得从认识一个 ...

  2. .NET Core采用的全新配置系统[9]: 为什么针对XML的支持不够好?如何改进?

    物理文件是我们最常用到的原始配置的载体,最佳的配置文件格式主要由三种,它们分别是JSON.XML和INI,对应的配置源类型分别是JsonConfigurationSource.XmlConfigura ...

  3. .NET Core采用的全新配置系统[1]: 读取配置数据

    提到“配置”二字,我想绝大部分.NET开发人员脑海中会立马浮现出两个特殊文件的身影,那就是我们再熟悉不过的app.config和web.config,多年以来我们已经习惯了将结构化的配置定义在这两个文 ...

  4. .NET Core采用的全新配置系统[2]: 配置模型设计详解

    在<.NET Core采用的全新配置系统[1]: 读取配置数据>中,我们通过实例的方式演示了几种典型的配置读取方式,其主要目的在于使读者朋友们从编程的角度对.NET Core的这个全新的配 ...

  5. .NET Core采用的全新配置系统[3]: “Options模式”下的配置是如何绑定为Options对象

    配置的原子结构就是单纯的键值对,并且键和值都是字符串,但是在真正的项目开发中我们一般不会单纯地以键值对的形式来使用配置.值得推荐的做法就是采用<.NET Core采用的全新配置系统[1]: 读取 ...

  6. .NET Core采用的全新配置系统[5]: 聊聊默认支持的各种配置源[内存变量,环境变量和命令行参数]

    较之传统通过App.config和Web.config这两个XML文件承载的配置系统,.NET Core采用的这个全新的配置模型的最大一个优势就是针对多种不同配置源的支持.我们可以将内存变量.命令行参 ...

  7. C# 读取app.config配置文件 节点键值,提示 "配置系统未能初始化" 错误的解决方案

    新建C#项目,在app.config中添加了appSettings项,运行时出现"配置系统未能初始化"的错误,MSDN里写到,如果配置文件中包含 configSections 元素 ...

  8. App.config“配置系统未能初始化” 异常解决 C#

    System.Configuration.ConfigurationManager.AppSettings["user"]; 时出现“配置系统未能初始化” 错误 解决办法: 如果配 ...

  9. CSipSimple配置系统

    称作配置系统未免太大了一点,不过它的配置管理这一块确实有加以设计,一方面以增加灵活性,另一方面以支持第三方扩展.通过分析源码,粗略画出如下的结构图: 一.类分析 SharedPreference 一切 ...

  10. C# “配置系统未能初始化” 异常解决

    使用App.config配置参数,读取参数出现错误 “System.Configuration.ConfigurationErrorsException”类型的未经处理的异常在 System.Conf ...

随机推荐

  1. MySQL - [08] 存储过程

    题记部分 一.什么是存储过程   存储过程是事先经过编译并存储在数据库中的一段SQL语句的集合,调用存储过程可以简化应用开发人员的很多工作,减少数据在数据库和应用服务器之间的传输,对于提高数据处理的效 ...

  2. 基于Unity调取摄像头方式的定时抓拍保存图像方法小结

    上一篇<Maxmspjitter实现实时抓取摄像头画面并制成序列图 (定时抓拍)>已讲到了定时抓拍的相关问题解决方案,这一篇继续,采用不同的方法,不同的平台----基于Unity. 目标明 ...

  3. 【渗透测试】Vulnhub Hackable II

    渗透环境 攻击机:   IP: 192.168.216.129(Kali) 靶机:     IP:192.168.216.131 靶机下载地址:https://www.vulnhub.com/entr ...

  4. Kali Linux(202104)重置root账户密码

    1.前言 如果忘记了Kali Linux系统的登录密码,最关键的需求就是重置root用户的登录密码, 之后使用root账户可以修改其他账户的密码. 因此, 本文就介绍一下在不知道root用户登录密码的 ...

  5. 【Verilog】表达式位宽与符号判断机制

    缘起于p1课下alu算数位移设计.查了好多资料,最后发现还是主要在翻译官方文档.浪费了超多时间啊,感觉还是没搞透,还是先以应用为导向放一放,且用且归纳 1.表达式位宽 expression bit l ...

  6. 常用损失函数 LossFunction

    文章结构 损失函数在神经网络中的位置 常用的损失函数(结构:解释,公式,缺点,适用于,pytorch 函数) MAE/L1 Loss MSE/L2 Loss Huber Loss 对信息量.熵的解释 ...

  7. python ImportError: libGL.so.1: cannot open shared object file: No such file or directory

    前言 python 报错python ImportError: libGL.so.1: cannot open shared object file: No such file or director ...

  8. Kubernetes的工作机制

    云计算时代的操作系统 Kubernetes 是一个生产级别的容器编排平台和集群管理系统,能够创建.调度容器,监控.管理服务器. Kubernetes 的基本架构 操作系统的一个重要功能就是抽象,从繁琐 ...

  9. Win10下子系统Unbuntu18.04安装nginx

    1.Nginx的软件包在Ubuntu默认软件仓库中可用. 安装非常简单,只需键入以下命令: sudo apt update sudo apt install nginx 2.安装完成后,检查Nginx ...

  10. mysql [ERR] 1273 - Unknown collation: 'utf8mb4_0900_ai_ci'

    这是因为当前数据库版本较高,需要更改一些参数 解决方法: 将sql文件中的 utf8mb4_0900_ai_ci替换为utf8_general_ci utf8mb4替换为utf8 再次运行SQL文件即 ...