Friday, June 13, 2008

Add, Update, Delete Key Value in Web Configuration File from Code Behind

Add Key:

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings
=(AppSettingsSection)objConfig.GetSection("appSettings");
objAppsettings.Settings.Add("apiusername", "ehsan4u");
objAppsettings.Settings.Add("apipassword", "ehsan4u");
objConfig.Save();

Note: It is not recommended as any change in the web.config file will restart the Web server and refresh the cache entries.

Read Key Value:

Specific Key Value:

ConfigurationSettings.AppSettings["apiusername"]

All key Value:

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings =
(AppSettingsSection)objConfig.GetSection("appSettings");

if (objAppsettings != null) {

foreach (string key in appSettings.Settings.AllKeys) {
  string value = appSettings.Settings[key].Value;
   Response.Write(string.Format("Key: {0} Value: {1}", key, value));
}
}


Update a Value:

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings =

(AppSettingsSection)objConfig.GetSection("appSettings");

if (objAppsettings != null){

objAppsettings.Settings[strKey].Value = strValue;
objConfig.Save();
}

Remove

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");

AppSettingsSection objAppsettings =

(AppSettingsSection)objConfig.GetSection("appSettings");

if (objAppsettings != null){

objAppsettings.Settings.Remove(key);

objConfig.Save();

}

Reference:

http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection.aspx

No comments: