C# 读取 AppConfig 配置文件的内容

一、配置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”的同步文件,在程序运行中不会发生更改。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值