Wednesday 8 July 2009

Save Settings to Web.Config file

Here's a quick snippet showing how to save a setting back to the web.config file. You are best wrapping this block in a try/catch in case the ASPNET user (or equivalent) does not have write access permissions to the file.

Configuration config = WebConfigurationManager.OpenWebConfiguration( "~/" );
AppSettingsSection appSettings = config.GetSection( "appSettings" ) as AppSettingsSection;

if ( appSettings != null )
{
if ( appSettings.Settings ["mySetting"] != null )
{
appSettings.Settings.Remove( "mySetting" );
}
appSettings.Settings.Add( "mySetting", text );
}
config.Save( ConfigurationSaveMode.Modified );

No comments: