.net core —— 控制台如何获取配置文件的内容?

本文链接:https://blog.csdn.net/yenange/article/details/82457761
参考: https://github.com/liuzhenyulive/JsonReader

在  Web 应用程序中, 获取配置文件还是比较简单的, 可以参考: 

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1#json-configuration-provider

但在控制台和类库中如何处理呢?

为了与 Web 保持一致, 配置文件名称还是使用:

appsettings.json

{
"ServerCode": "99",
"section0": {
"UserId": "1",
"UserName": "Tome"
},
"section1": {
"UserId": "2",
"UserName": "Marry"
}
}
下面展示了直接取字符串、绑定到实体及取子节点的几种方式:

using Microsoft.Extensions.Configuration;
using System;

namespace ConsoleApp4
{
class Program
{
//安装 .net core 2.1 完整包
//install-package Microsoft.AspNetCore.All -version 2.1.0
//注意不要超过 依赖项->SDK->Microsoft.NETCore.App 的版本,我这里是 2.1.0
//否则会无法正常生成和运行
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
Console.WriteLine($"ServerCode:{configuration["ServerCode"]}");
UserInfo user1 = new UserInfo();
UserInfo user2 = new UserInfo();
configuration.GetSection("section0").Bind(user1);
configuration.GetSection("section1").Bind(user2);

Console.WriteLine(user1.ToString());
Console.WriteLine(user2.ToString());
Console.WriteLine($"section0:UserId:{configuration["section0:UserId"]}");
Console.Read();
}
}

public class UserInfo
{
public long UserId { get; set; }
public string UserName { get; set; }

public override string ToString()
{
return string.Format($"UserId:{UserId}, UserName:{UserName}");
}
}
}


还有一个问题: UserName 后面的值, 如果换成中文, 会显示乱码, 这个如何解决?

经 lindexi_gd 兄指点, 用 notepad++ 打开 json 文件, 改成 utf-8 编码, 就可以读取中文了, 表示感谢!


————————————————
版权声明:本文为CSDN博主「吉普赛的歌」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yenange/article/details/82457761

原文地址:https://www.cnblogs.com/webenh/p/11693867.html