LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C# 读写Json格式配置文件

admin
2024年4月11日 13:59 本文热度 65

摘要


为了兼容,仍然可以使用Web.config,App.config 和ConfigurationManager类,但不推荐。

.NET中的配置系统支持丰富的配置源,包括文件(json、xml、ini等)、注册表、环境变量、命令行、Azure Key Vault等,还可以配置自定义配置源。可以跟踪配置的改变,可以按照优先级覆盖。

正文


Json文件配置

  • 创建一个ison文件,文件名随意,比如config.json,设置“如果较新则复制”。参考备注

  • NuGet安装Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json

一个例子

在项目中添加一个json文件

编写一下json

{  "Email": "admin@admin.com",  "Name": "admin",  "Password": "123456",  "SmtpServer": "smtp@admin.com",  "DbInfo": {    "Uid": "sa",    "Password": "123",    "Ip": "127.0.0.1"  }}

读取

private void btnRead_Click(object sender, EventArgs e){    ConfigurationBuilder builder = new ConfigurationBuilder();    builder.AddJsonFile("config.json", true, true);    IConfigurationRoot root=builder.Build();    txtEmail.Text = root["Email"];    txtName.Text = root["Name"];    txtPassword.Text = root["Password"];    txtSmtp.Text = root["SmtpServer"];    txtUid.Text = root["DbInfo:Uid"];//多层次用:}

我们还可以用类映射的方式来读取

声明一个DbInfo类

public class DbInfo{    public string Uid { get; set; }    public string Password { get; set; }    public string Ip { get; set; }}

安装包 Microsoft.Extensions.Configuration.Binder

var db=root.GetSection("DbInfo").Get<DbInfo>();txtUid.Text = db.Uid;txtDbPassword.Text = db.Password;txtIp.Text = db.Ip;

修改一下DbInfo类

public class DbInfo{    public static string Uid { get; set; }    public static string Password { get; set; }    public static string Ip { get; set; }
   public static List<string> Ips { get; set; }=new List<string>();}

在Program中读取

ConfigurationBuilder builder = new ConfigurationBuilder();builder.AddCommandLine(args);IConfigurationRoot root= builder.Build();
DbInfo.Ip =root["server"];DbInfo.Uid = root["uid"];DbInfo.Password = root["password"];
DbInfo.Ips.Add(root["ips:0"]);DbInfo.Ips.Add(root["ips:1"]);


该文章在 2024/4/11 15:24:02 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved