How to use the config file



Add System.Configuration.dll reference

Referencing the using System.Configuration namespace


The method of reading the appSettings section of the config file is relatively simple, which can be accessed through the method of System.Configuration.ConfigurationManager.AppSettings["Key"] above, but this method does not provide writing.


If you want to write a configuration file, you can use the ConfigurationManager object to perform the operation of opening the configuration file, and it will return a Configuration object, which can be used for operations (addition, deletion, modification, and query are all possible).


privatevoid AccessAppSettings()
{
//获取Configuration对象
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//根据Key读取<add>元素的Value
string name = config.AppSettings.Settings["name"].Value;
//写入<add>元素的Value
config.AppSettings.Settings["name"].Value ="xiao";
//增加<add>元素
config.AppSettings.Settings.Add("url","http://www.baidu.com");
//删除<add>元素
config.AppSettings.Settings.Remove("name");
//一定要记得保存,写不带参数的config.Save()也可以
config.Save(ConfigurationSaveMode.Modified);
//刷新,否则程序读取的还是之前的值(可能已装入内存)
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325837667&siteId=291194637