一、配置App.config
<!--//预定义配置节-->
<appSettings>
<add key="test1" value="test1_value1"/>
<add key="test2" value="test2_value2"/>
</appSettings>
二、读取配置文件
//获取Configuration对象
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//根据Key读取<add>元素的Value
string test1 = config.AppSettings.Settings["test1"].Value;
string test2 = config.AppSettings.Settings["test2"].Value;
Console.WriteLine(test1);
Console.WriteLine(test2);
//写入<add>元素的Value
config.AppSettings.Settings["test1"].Value = "test1test1test1";
config.AppSettings.Settings["test2"].Value = "test2test2test2";
//增加<add>元素
config.AppSettings.Settings.Add("url", "http://www.fx163.net");
//删除<add>元素
config.AppSettings.Settings.Remove("test2");
//一定要记得保存,写不带参数的config.Save()也可以
config.Save(ConfigurationSaveMode.Modified);
Console.WriteLine(test1);
Console.WriteLine(test2);
//刷新,否则程序读取的还是之前的值(可能已装入内存)
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
三、说明
1. 配置文件
常见配置文件模式:
<configuration>
<configSections> //配置节声明区域,包含配置节和命名空间声明
<section> //配置节声明
<sectionGroup> //定义配置节组
<section> //配置节组中的配置节声明
<appSettings> //预定义配置节
<Custom element for configuration section> //配置节设置区域
2. 文件生成
在项目进行编译后,在运行目录bin\Debuge文件下,将出现两个配置文件,
一个名为“ProjectName.exe.config”,另一个名为“ProjectName.vshost.exe.config”。
第一个文件为项目实际使用的配置文件,在程序运行中所做的更改都将被保存于此;
第二个文件其实为原代码中“App.config”的同步文件,在程序运行中不会发生更改。