views:

1148

answers:

3

In my application, I need to change some value ("Environment") in appSetting of app.config at runtime.

I use AppSettingsReader

    private static AppSettingsReader _settingReader;

    public static AppSettingsReader SettingReader
    {
        get 
        {
            if (_settingReader == null)
            {
                _settingReader = new AppSettingsReader();
            }
            return _settingReader; 
        }
    }

Then at some stage I do this

        config.AppSettings.Settings[AppSettingString.Environment.ToString()].Value = newEnvironment.ToString();
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

However, next time I try to read "Environment" like this

       string environment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));

I end up with the old value of Environment.

I noticed that I can fix this by doing

_settingReader = new AppSettingsReader();

before I read "Environment".

But I think creating a new instance is not the proper approach.

Maybe there is a way to let my SettingReader know, that the values have changed to use the same instance of it, but with refreshed values?

(Not a project-breaking question obviously, more of an educational one)

A: 

System.Configuration.ApplicationSettingsBase.Reload

Jonathan Allen
+1  A: 

AppSettingsReader doesn't seem to have any method to reload from disk. It just derives from Object. Creating a new instance seems to be the only thing that would work... I may be wrong, but AppSettings are supposed to be read-only values for your app. More like configuration parameters for your application that can be tweaked before startup.

For read-write application settings, I think the Settings mechanism with IDE support (System.Configuration.ApplicationSettingsBase) would be the preferred approach. This has Save and Reload methods. The designer-gen class makes the code far more readable too..
Double click on the Properties Node under your Project in Solution Explorer. Find the Settings tab.

Instead of

sEnvironment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));

you could have typed properties like

sEnvironment = Properties.Settings.Default.Environment;

The designer generated class exposes a synchronized singleton instance via the Default property.. which should mean you don't need to reload.. you'd always get the latest value within the application.

Gishu
A: 

Upgrade is the function you are looking for

System.Configuration.ApplicationSettingsBase.Upgrade
Locutus