If you need flexible operation and reading and writing configuration files in .net1.1, it is not very convenient. Generally, a configuration file management class is encapsulated in the project to perform reading and writing operations. In .net2.0, the ConfigurationManager and WebConfigurationManager classes can be used to manage configuration files very well. The ConfigurationManager class is in System.Configuration and the WebConfigurationManager is in System.Web.Configuration. According to MSDN, for Web application configuration, it is recommended to use the System.Web.Configuration.WebConfigurationManager class instead of the System.Configuration.ConfigurationManager class.
Below I give a simple example to illustrate how to use WebConfigurationManager to operate configuration files:
//Open configuration file
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
//Get the appSettings node
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
//Add elements in the appSettings node
appSection.Settings.Add("addkey1", "key1's value");
appSection.Settings.Add("addkey2", "key2's value");
config.Save();
After running the code, you can see the changes in the configuration file:
<appSettings>
<add key="addkey1" value="key1's value" />
<add key="addkey2" value="key2's value" />
</appSettings>
It is also very convenient to modify and delete nodes or attributes:
//Open the configuration file
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
//Get the appSettings node
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
//Delete elements in the appSettings node
appSection.Settings.Remove("addkey1");
//Modify elements in the appSettings node
appSection.Settings["addkey2"].Value = "Modify key2's value";
config.Save();
Configuration file:
<appSettings>
<add key="addkey2" value="Modify key2's value" />
</appSettings>
Reference: http://msdn2.microsoft.com/en-us/library/ms228060.aspx