C#中動態讀取配置

有些時候,文件修改須要及時的響應,這個時候就須要實時讀取文件,預先想的是寫一個計時器,每隔多久運行一次,可是不能實時響應,因此採用監聽文件的方式實現讀取數據web

C#監聽文件變化

/// <summary>
/// 監聽文件變化
/// </summary>
private static void WatcherFile()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Environment.CurrentDirectory;
    watcher.Filter = "*.config";

    watcher.Changed += (object sender, FileSystemEventArgs e) => {
        Thread.Sleep(100);
        FetchData();
    };
    watcher.EnableRaisingEvents = true;
}

C#讀取配置文件

讀取配置文件中的數據通常用ConfigurationManager.AppSettings["key"],web的配置文件更新以後會實時更新, 應用程序的配置文件不會實時更新,更新應用程序的配置文件以後需刷新不然讀取的仍是原來的舊數據。spa

ConfigurationManager.RefreshSection("key");
ConfigurationManager.AppSettings["key"];
相關文章
相關標籤/搜索