45

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.

Kieran Benton
  • 8,739
  • 12
  • 53
  • 77

10 Answers10

57

Make sure you are passing the correct case sensitive value to RefreshSection, i.e.

ConfigurationManager.RefreshSection("appSettings");
G-Wiz
  • 7,370
  • 1
  • 36
  • 47
  • 5
    And how would you just refresh the whole file? – jjxtra Jun 24 '12 at 04:45
  • This works. Just get the section name spelling right. For example: "connectionStrings". – Chris Patterson Feb 14 '13 at 17:28
  • 1
    I know this is an old post but still: RefreshSection is not a method in WebConfigurationManager class. So I am keen to know if ConfigurationManager.RefreshSection will refresh web.config also? – Shashi Oct 23 '14 at 06:54
  • 1
    @Shashi changing web.config will restart your web site, anyway. So there's no use in adding that method to the WebConfigurationManager class. – Tom Lint Nov 08 '15 at 17:14
  • 5
    Beware that changing app.config will not affect the programme being debugged. If you want to refresh the values during the debug time you should change .vshost.exe.config to see the changes. However, it works just as described when you run the application by itself. – map Apr 05 '17 at 13:01
  • 1
    Does not work when app.config is external file, at least for me it did not work – TarmoPikaro Apr 15 '20 at 10:37
16

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.

  • 5
    I've noticed the same. Any solutions? – Martin Jan 08 '16 at 11:29
  • Same problem here for my app (not web). I have a custom Section called "AdminSettings", and regardless of saving it in an external file or bring it back to my app.config, I cannot read the updated key/values while the app is running. I think it might be related to the section name, maybe there is a fully qualified name for sections? I tried things like "configration/Settings" or such, none worked! :/ – Siavash Mortazavi Nov 02 '20 at 22:15
5

For some reason ConfigurationManager.RefreshSection("appSettings") wasn't working for me. Reloading the Web.Config into a Configuration object seems to work correctly. The following code assumes the Web.Config file is one directory below the executing (bin) folder.

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
Uri uriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
string appPath = uriAssemblyFolder.LocalPath;
configMap.ExeConfigFilename = appPath + @"\..\" + "Web.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); 

And is used like:

string webConfigVariable = config.AppSettings.Settings["webConfigVariable"].Value;
Willem van Ketwich
  • 5,666
  • 7
  • 49
  • 57
4

.RefreshSection() does not work when the appSettings is external.

You can however use the following to change a value:

ConfigurationManager.AppSettings.Set(key, value)

This will NOT change the setting on file, only the loaded value in memory.

So instead of using RefreshSection I did the following:

string configFile="path to your config file";
XmlDocument xml = new XmlDocument();
xml.Load(configFile);

foreach (XmlNode node in xml.SelectNodes("/appSettings/add"))
{
    string key = node.Attributes["key"].Value;
    string value= node.Attributes["value"].Value;
    ConfigurationManager.AppSettings.Set(key, value);
}

Any subsequent calls to AppSettings.Get will contain the updated value.

The appSettings will then be updated without needing to restart the application.

Allie
  • 1,081
  • 1
  • 13
  • 17
3

As an alternative you could write your own ConfigSection and set restartOnExternalChanges="false".

Then, when reading the section with ConfigurationManager.GetSection("yourSection") the settings will be auto-refreshed without an application restart.

And you could implement your settings strongly typed or as NameValueCollection.

Martin Meixger
  • 2,547
  • 24
  • 26
0

Yes. you are stuck with iis restarting.

There is a feature with asp.net 4.0 and iis 7.5 where the initial startup is removed.

yamspog
  • 18,173
  • 17
  • 63
  • 95
0

I am not sure if this is possible in a web app, but it works in a desktop app. Try using ConfigurationSettings rather than ConfigurationManager (it will yell at you for using outdated classes...), then reading all the data into a class. When you wish to refresh, simply create a new instance and drop all references to the old instance. My theory for why this works (might be wrong): when you don't directly access the app.config file the entire time you are running, the file lock is dropped by the application. Then, edits can be made when you are not accessing the file.

badpanda
  • 2,446
  • 5
  • 34
  • 45
-1

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.

Seibar
  • 68,705
  • 38
  • 88
  • 99
  • So what is http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.refreshsection.aspx for? – Kieran Benton Oct 07 '08 at 16:43
  • Good question - I don't know :) – Seibar Oct 07 '08 at 17:00
  • @Terrapin: Please try the RefreshSection method as suggested by KieranBenton, it works. See my answer in this SO thread: http://stackoverflow.com/questions/272097/net-dynamically-refresh-app-config – Sudhanshu Mishra Jul 11 '12 at 06:08
  • Have to say though: I have not tried this in a web app. I would assume this should be of help: http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.restartonexternalchanges (you would need to explicitly set `SectionInformation.RestartOnExternalChanges`) EDIT: just noticed that Meixger has already suggested this – Sudhanshu Mishra Jul 11 '12 at 06:10
-1

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
C. Ross
  • 31,137
  • 42
  • 147
  • 238
-2

Have you tried storing your AppSettings in its own external file?

From app.config/web.config:

<appSettings configSource="appSettings.config"></appSettings>

appSettings.config:

<?xml version="1.0"?>
<appSettings>
  <add key="SomeKey" value="SomeValue" />
</appSettings>

Changes made to appSettings.config should be reflected instantly. More info: http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx

Vince
  • 617
  • 8
  • 18
  • 2
    I beleive the OP is already using an external file. His question pertains to reflecting the changes made in the external file without an application (or app domain) restart – Sudhanshu Mishra Jul 11 '12 at 06:16
  • Agreed with dotnetguy. He's already doing this - this is his problem - doing this and not being able to refresh the changes made to it on the fly. – vapcguy Jul 18 '17 at 15:24