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"];
相关文章
相关标签/搜索