摘要
為了兼容,仍然可以使用Web.config,App.config 和ConfigurationManager類,但不推薦。
.NET中的配置系統(tǒng)支持豐富的配置源,包括文件(json、xml、ini等)、注冊(cè)表、環(huán)境變量、命令行、Azure Key Vault等,還可以配置自定義配置源??梢愿櫯渲玫母淖?,可以按照優(yōu)先級(jí)覆蓋。
正文
Json文件配置
創(chuàng)建一個(gè)ison文件,文件名隨意,比如config.json,設(shè)置“如果較新則復(fù)制”。參考備注
NuGet安裝Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json
一個(gè)例子
在項(xiàng)目中添加一個(gè)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"];//多層次用:
}
我們還可以用類映射的方式來讀取
聲明一個(gè)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 編輯過