- Open Web.Config for editing using
WebConfigurationManagerclass. - Using respective
Configurationclass, bring about the necessary changes. - Save changes to the physical file using
Configurationclass.
private void UpdateConfig(string strKey, string strValue)
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
if (objAppsettings != null)
{
objAppsettings.Settings[strKey].Value = strValue;
objConfig.Save();
}
}
In the above piece of code, OpenWebConfiguration() method of WebConfigurationManager class opens Web.Config file in the root directory and returns it as a Configuration object. GetSection() method of Configuration class accepts path to a specific section as argument. The path is the relative path from the root node "configuration". You can refer to deeper nodes(sections in our context) by their names separated by '/'. For example, to get access to the "authentication" section, provide "system.web/authentication" as the parameter to GetSection() method. It returns a generic ConfigurationSecton object, which can be typecasted to proper configuration section class. In our example we get hold of the "appSettings" section with the help of AppSettingsSection class. AppSettingsSection class instance has a Settings collection property which contains application setting from the configuration section as key-value pairs. The Settings property can be indexed using key to get the corresponding value. You can also set the value property and call the Save() method of the Configuration object to write configurations in the Configuration instance to config file.
To delete an entry in the Web.config file: The Remove() method of Settings collection deletes an entry from the Configuration instance. Remove() method accepts key of the entry to be deleted.
Note: Please do not forget to call the Save() method of the Configuration instance to get the chnages reflected in the physical file.
objAppsettings.Settings.Remove("Location");
To iterate through all the key-value pairs in a configuration section, access the string array of keys via
AllKeys property of
Settings collection.
foreach (string strKey in objAppsettings.Settings.AllKeys)
{
DataRow dr = dt.NewRow();
dr["Key"] = strKey;
dr["Value"] = objConfig.AppSettings.Settings[strKey].Value;
dt.Rows.Add(dr);
}
Comments