user2437909
user2437909

Reputation: 35

Can't Read appSettings until restart of application

Can someone help me understand why after adding a value to the config file, I cannot read it into the application right away? I do a refresh, but that doesn't work. See below:

    public void AddConfig(string key_value, string actual_value)
    {
        // Open App.Config of executable
        System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
        //If it exists, remove it first
        config.AppSettings.Settings.Remove(key_value);
        // Add an Application Setting.
        config.AppSettings.Settings.Add(key_value, actual_value);            
        // Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified);
        // Force a reload of a changed section.            
        ConfigurationManager.RefreshSection("appSettings");
        string blah = ConfigurationManager.AppSettings[key_value];
        MessageBox.Show(blah);
    }

The message box will show as null/blank.

If I restart the application and run another command to read the key value after startup, it will work.

Any ideas?

Upvotes: 2

Views: 305

Answers (1)

Metro Smurf
Metro Smurf

Reputation: 38335

What you're experiencing is very likely a due to running the application from within the Visual Studio environment.

Run the .exe directly from the Debug or Release directory and the RefreshSection() method will work as expected.

If you want to see the changed value while debugging, you'll need to use AppSettings.Settings instead of ConfigurationManager.AppSettings:

string blah = config.AppSettings.Settings[key_value].Value

Upvotes: 1

Related Questions