更新配置文件而不重启应用程序

时间:2012-06-08 11:55:05

标签: c# web-services

我试图在不关闭应用程序的情况下更新配置文件。问题是即时阅读缓存版本。我有一个不起作用的FileSystemWatcher。任何帮助表示赞赏

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


                }

        }

    }

1 个答案:

答案 0 :(得分:2)

在致电ConfigurationManager.RefreshSection("appSettings");之前,请致电appConfig.AppSettings.Settings["myConfigData"].Value;,这将迫使应用程序阅读新的&更改了设置。否则,ConfigurationManager本身会缓存所有值。