Reloading configuration without restarting application using ConfigurationManager.RefreshSection

Viewed 46819

Has anyone got this working in a web application?

No matter what I do it seems that my appSettings section (redirected from web.config using appSettings file=".\Site\site.config") does not get reloaded.

Am I doomed to the case of having to just restart the application? I was hoping this method would lead me to a more performant solution.

Update:

By 'reloading' I mean refreshing ConfigurationManager.AppSettings without having to completely restart my ASP.NET application and having to incur the usual startup latency.

10 Answers

This seems to be a flaw (maybe a bug) when using an external config file for your appSettings. I've tried it using the configSource attribute and RefreshSection simply never works, I'm assuming this is the same when using the file attribute. If you move your appSettings back inside your web.config RefreshSection will work perfectly but otherwise I'm afraid you're doomed.

The App.Config settings are cached in memory when the application starts. For this reason, I don't think you'll be able to change those settings without restarting your application. One alternative that should be pretty straight forward would be to create a separate, simple XML configuration file, and handle loading/caching/reloading it yourself.

To write, call it this way:

Dim config As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")

Return AddOrUpdateAppSetting(config, "YourSettingKey", "YourValueForTheKey")

To read and be sure you get the values in file, instead of those in cache, read it this way:

Dim config As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("~")
  Return config.AppSettings.Settings("TheKeyYouWantTheValue").Value

Full example:

Protected Shared Function AddOrUpdateAppSetting( _
       ByVal Config As System.Configuration.Configuration _
     , ByVal TheKey As String _
     , ByVal TheValue As String _
     ) As Boolean</p>

    Dim retval As Boolean = True

    Dim Itm As System.Configuration.KeyValueConfigurationElement = _
        Config.AppSettings.Settings.Item(TheKey)
    If Itm Is Nothing Then
        If Config.AppSettings.Settings.IsReadOnly Then
        retval = False
        Else
        Config.AppSettings.Settings.Add(TheKey, TheValue)
        End If


    Else
        ' config.AppSettings.Settings(thekey).Value = thevalue
        If Itm.IsReadOnly Then
            retval = False
        Else
            Itm.Value = TheValue
        End If


    End If
    If retval Then
     Try
        Config.Save(ConfigurationSaveMode.Modified)

     Catch ex As Exception
        retval = False
     End Try

    End If

    Return retval

End Function
Related