Jed I
Jed I

Reputation: 1038

update config file without restart application

I am trying to get around updating the config file without closing application. The problem is the im still reading cached version. I have a FileSystemWatcher which is not working. Any help appreciated

public partial class ChangeURL : Form
{

    Service ser = new Service();
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);



    public ChangeURL()
    {
        InitializeComponent();
        textBox1.Text = ser.Url;
        start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        changeSettings();
        this.Close();
    }
    public void changeSettings()
    {

        KeyValueConfigurationCollection settings = config.appSettings.Settings;

        try
        {
            ConfigurationManager.RefreshSection("appSettings");
            settings["client_postCodeRef_Service"].Value = textBox1.Text;
            ser.Url = settings["client_postCodeRef_Service"].Value;
            config.Save(ConfigurationSaveMode.Modified);


        }
        catch (ConfigurationErrorsException e)
        {
            MessageBox.Show("[Exception error: {0}]",
                e.ToString());
        }



     } // end change settings
                public void onChange(object source, FileSystemEventArgs e) 
                { 
                    ConfigurationManager.RefreshSection("appSettings"); 
                }
                public void start()
                {
                    FileSystemWatcher fileWatcher = new FileSystemWatcher();

                    if (fileWatcher == null)
                    {
                        string path = Path.GetDirectoryName(config.FilePath);
                        string filename = Path.GetFileName(config.FilePath);

                        fileWatcher = new FileSystemWatcher();
                        fileWatcher.Path = path;
                        fileWatcher.Filter = filename;
                        fileWatcher.NotifyFilter = (NotifyFilters.CreationTime | NotifyFilters.FileName);
                        fileWatcher.Changed += onChange;
                        fileWatcher.EnableRaisingEvents = true;

                    } // endif


                }

        }

    }

Upvotes: 0

Views: 2260

Answers (1)

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20775

Just call ConfigurationManager.RefreshSection("appSettings"); before you call appConfig.AppSettings.Settings["myConfigData"].Value; which will force the application to read the new & changed settings. Otherwise, ConfigurationManager inherently caches all values.

Upvotes: 2

Related Questions