使用.Net2.0中的ConfigurationManager可以方便的实现对配置app.config的读取和写入。

ConfigurationManager默认没有自动载入项目,使用前必须手动添加,方法如下:

项目->引用->添加引用->选择System.configuration

1.使用ConfigurationManager读配置文件

我们可以将简单的配置内容放到app.config中的appSettings节点中如下:

<appSettings>
  <add key="GPRS.Port1" value="5002"/>
  <add key="GPRS.Port2" value="5003"/>
  <add key="GPRS.Port3" value="5004"/>
</appSettings>

然后在程序中使用ConfigurationManager.AppSettings["GPRS.Port1"]来读取GPRS.Port1的值

2.使用ConfigurationManager写配置文件

如何想要把修改过的GPRS.Port1的值存放回app.config,可以使用下面的代码

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["GPRS.Port1"].Value = “xxxxx”;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/tjvictor/archive/2009/12/03/4933761.aspx

posted on 2010-01-21 20:05  WPF之家  阅读(696)  评论(0编辑  收藏  举报