1

As the question title states, I'm saving some application settings (currently just a database path) to the application configuration file. The changes seem to save into the file ok, but when I then try to read the new data I get an empty string. The new data reads in fine if I restart the application, but I do need it to read in without having to restart the app. My config settings class is below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Windows.Forms;

namespace HADDMS_Asset_Management_System
{
    public static class ConfigSettings
    {
        public static bool WriteSetting(string key, string value)
        {
            try
            {
                System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.AppSettings.Settings[key].Value = value;
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(key);
            }
            catch (Exception e)
            {
                MessageBox.Show("Error writing to configuration settings:\r\n" + e.ToString());
                return false;
            }

            return true;
        }

        public static string ReadSetting(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        public static string ReadSetting(int keyIndex)
        {
            return ConfigurationManager.AppSettings[keyIndex];
        }
    }
}

Edit: I should add that I am running the application from the release folder.

jeremy
  • 9,965
  • 4
  • 39
  • 59
T_Bacon
  • 404
  • 6
  • 22
  • possible duplicate of [Changing App.config at Runtime](http://stackoverflow.com/questions/2008800/changing-app-config-at-runtime) – Nahum Dec 24 '13 at 12:04

1 Answers1

2

The problem is you are attempting to refresh a section named key, which doesn't exist. You need to replace your call to RefreshSection() with this:

ConfigurationManager.RefreshSection("appSettings");

You can test this out by doing this:

//keySection will be null
var keySection = config.GetSection(key);

The ConfigurationManager will apparently not throw an error when there is no section found matching the name provided to RefreshSection() which is interesting.

Sven Grosen
  • 5,616
  • 3
  • 30
  • 52