Managing Configuration Data Programmatically in ASP.NET 2.0
链接:http://aspalliance.com/1637_Managing_Configuration_Data_Programmatically_in_ASPNET_20.all
Listing 1
Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSettingsSection =
(AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
{
foreach (string key in appSettingsSection.Settings.AllKeys)
{
Response.Write(key);
}
}
The following method can be used to update a specific key - value pair in the web.config file.
Listing 2
public void Update(string key, string value)
{
Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSettingsSection =
(AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
{
appSettingsSection.Settings[key].Value = value;
config.Save();
}
}
The following method can be used to delete a specific key in the web.config file.
Listing 3
public void Delete(string key)
{
Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSettingsSection =
(AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
{
appSettingsSection.Settings.Remove(key);
config.Save();
}
}