C#读取和写入配置文件

使用.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 TJVictor专栏:http://blog.csdn.net/tjvictor

原文地址:https://www.cnblogs.com/hyshareex/p/3809352.html