Wednesday, October 31, 2007

Changing AppSettings in .NET

Using appsettings("key")=value . Will change the settings in memory and not in web.config

To change it in both, use this method:

VB:

Private Sub ChangeAppSettings(ByVal key As String, ByVal NewValue As String)
Dim cfg As Configuration
cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")

Dim setting As KeyValueConfigurationElement = _
CType(cfg.AppSettings.Settings(key), KeyValueConfigurationElement)

If Not setting Is Nothing Then
setting.Value = NewValue
cfg.Save()
End If
End Sub

C#:

private void ChangeAppSettings(string key, string NewValue)
{
Configuration cfg;
cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

KeyValueConfigurationElement setting = (KeyValueConfigurationElement)cfg.AppSettings.Settings(key);

if ((setting != null)) {
setting.Value = NewValue;
cfg.Save();
}
}

No comments: