The sections that usually contain sensitive information that
we need to encrypt are the following:
<appSettings>: This section contains custom
application settings.
<connectionStrings>: This section contains connection
strings.
<identity>: This section can contain impersonation
credentials.
<sessionState>: The section contains the connection
string for the out-of-process session state provider.
The following code snippet displays all the keys of the
appSettings section of the web.config file.
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();
}
}