摘要
C# 是一种常用的面向对象编程语言,常用于开发 Windows 应用程序、Web 应用程序和游戏等。C# 的开发者可以使用 Configuration 类来读取 INI 文件。INI 文件是一种常见的配置文件格式,它可以存储一些配置信息,如程序的数据、用户的偏好设置等。
正文
安装Microsoft.Extensions.Configuration.Ini
创建一个ini文件
[DbInfo]
Server=127.0.0.1
Uid=sa
password=123
DataBase="TestDb"
[EmailInfo]
Email="[email protected]"
Name="admin"
Password="123"
SmtpServer="[email protected]"
创建一个DbInfo类
public class DbInfo
{
public static string Uid { get; set; }
public static string Password { get; set; }
public static string Ip { get; set; }
}
读取配制
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddIniFile("config.ini");
IConfigurationRoot root= builder.Build();
DbInfo.Ip =root["DbInfo:Server"];
DbInfo.Uid = root["DbInfo:Uid"];
DbInfo.Password = root["DbInfo:Password"];
映射到类
var emailInfo=root.GetSection("EmailInfo").Get<EmailInfo>();
读取到界面
private void btnRead_Click(object sender, EventArgs e)
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddIniFile("config.ini");
IConfigurationRoot root = builder.Build();
DbInfo.Ip = root["DbInfo:Server"];
DbInfo.Uid = root["DbInfo:Uid"];
DbInfo.Password = root["DbInfo:Password"];
var emailInfo = root.GetSection("EmailInfo").Get<EmailInfo>();
txtUid.Text = DbInfo.Uid;
txtDbPassword.Text = DbInfo.Password;
txtIp.Text = DbInfo.Ip;
txtEmail.Text = emailInfo.Email;
txtPassword.Text= emailInfo.Password;
txtName.Text = emailInfo.Name;
txtSmtp.Text = emailInfo.SmtpServer;
}