App.config应用
date
Aug 20, 2023
slug
10068
status
Published
tags
C#
summary
type
Post
右键项目,添加item

添加一组配置信息

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Email" value="admin@admin.com"/>
<add key="Password" value="123456"/>
<add key="SmtpServer" value="smtp.admin.com"/>
</appSettings>
</configuration>
代码
using System.Configuration;
using System.Windows;
namespace WpfApp3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void buttonOpen_Click(object sender, RoutedEventArgs e)
{
var appSettings = ConfigurationManager.AppSettings;
txtEmail.Text = appSettings["Email"]?.ToString();//根据Key读取<add>元素的Value
txtPassword.Text = appSettings["Password"]?.ToString();//根据Key读取<add>元素的Value
txtSmtp.Text = appSettings["SmtpServer"]?.ToString();//根据Key读取<add>元素的Value
}
private void buttonUpdate_Click(object sender, RoutedEventArgs e)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Email"].Value = txtEmail.Text;//写入<add>元素的Value
config.AppSettings.Settings["Password"].Value = txtPassword.Text;//写入<add>元素的Value
config.AppSettings.Settings["SmtpServer"].Value = txtSmtp.Text;//写入<add>元素的Value
config.AppSettings.Settings.Add("url", "http://www.google.com");//增加<add>元素
config.AppSettings.Settings.Remove("name");//删除<add>元素
config.AppSettings.SectionInformation.ForceSave = true;//保存文件
config.Save(ConfigurationSaveMode.Modified);//一定要记得保存,写不带参数的config.Save()也可以
//重新加载改变的节点
ConfigurationManager.RefreshSection("appSettings");//刷新,否则程序读取的还是之前的值(可能已装入内存)
}
}
}
注意,实际应用的时候,config文件会在debug目录下面,名字为
XXXXX.exe.Config
另一个例子:
using System;
using System.Configuration;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ReadAllSettings();
ReadSetting("Setting1");
ReadSetting("NotValid");
AddUpdateAppSettings("NewSetting", "May 7, 2014");
AddUpdateAppSettings("Setting1", "May 8, 2014");
ReadAllSettings();
}
static void ReadAllSettings()
{
try
{
var appSettings = ConfigurationManager.AppSettings;
if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
}
}
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
static void ReadSetting(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "Not Found";
Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
}
}