摘要
在C#中,ConfigurationManager类提供了一种方便的方式来读取和操作应用程序的配置文件。应用程序的配置文件通常位于应用程序的工作目录下,文件名为App.config或Web.config。通过使用ConfigurationManager类,我们可以读取这些文件中的数据,并在应用程序中使用这些数据。
正文
“System.Configuration.ConfigurationSettings.AppSettings”
“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
创建一个配制文件
右键项目,添加一个item
在.net 6下默认文件内容
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
我们添加一组邮箱配制信息
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Email" value="[email protected]"/>
<add key="Password" value="123456"/>
<add key="SmtpServer" value="smtp.admin.com"/>
</appSettings>
</configuration>
安装System.Configuration.Config
读取配制
private void btnRead_Click(object sender, EventArgs e)
{
txtEmail.Text = ConfigurationManager.AppSettings["Email"].ToString();
txtPassword.Text = ConfigurationManager.AppSettings["Password"].ToString();
txtSmtp.Text = ConfigurationManager.AppSettings["SmtpServer"].ToString();
}
修改数据
private void btnUpdate_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Email"].Value = txtEmail.Text;
config.AppSettings.Settings["Password"].Value = txtPassword.Text;
config.AppSettings.Settings["SmtpServer"].Value = txtSmtp.Text;
config.AppSettings.SectionInformation.ForceSave = true;//保存文件
config.Save(ConfigurationSaveMode.Modified);
//重新加载改变的节点
ConfigurationManager.RefreshSection("appSettings");
}