[.NET][Winform, Console]即時更新app.config的設定(FileSystemWatcher)

  • 955
  • 0

[.NET][Winform, Console]即時更新app.config的設定(FileSystemWatcher)

當winform or console程式的.exe執行中的時候,有時候總是希望可以改一下app.config的設定,並且不想去關閉.exe並重新啟動
只要利用FileSystemWatcher類別就能達成這個機制囉:
step1:在form_load或是程式剛開始執行的時候,加入FileSystemWatcher的監控
Step2:定義OnChanged()函數

private void ResultForm_Load(object sender, EventArgs e)
{
	string yourParam = "";
	yourParam = ConfigurationManager.AppSettings["yourKey"];//初始化讀取appsettings的參數

	private FileSystemWatcher watcher;
	string assemblyDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
	NotifyFilters notifyFilters = NotifyFilters.LastWrite;
	string filter = "*.config";
	watcher = new FileSystemWatcher() { Path = assemblyDirectory, NotifyFilter = notifyFilters, Filter = filter };
	//當檔案變更的時候,觸發OnChanged()事件
	watcher.Changed += OnChanged;
	watcher.EnableRaisingEvents = true;
	
}



//定義OnChanged()事件
private void OnChanged(object source, FileSystemEventArgs e)
{
	try
	{
		//暫時將FileSystemWatcher的觸發事件關閉,趁此時更新app.config設定
		watcher.EnableRaisingEvents = false;
		//重新從app.config檔案讀取appSettings區塊的設定
		ConfigurationManager.RefreshSection("appSettings");
		yourParam = ConfigurationManager.AppSettings["yourKey"];//再次讀取appsettings的參數

	}
	finally
	{
		watcher.EnableRaisingEvents = true;//更新完畢yourParam參數之後,再次把FileSystemWatcher的觸發事件開啟
	}
}

測試方法:
如果是在Visual Studio的debug階段,記得要去改OOXX.vshost.exe.config的設定檔,才能進入OnChange事件喔
如果已經發行到正式機的話,改OOXX.exe.config就可以進入OnChanged事件了
大概是這樣………