可以为我自己的配置文件模拟web.config重新启动行为

本文关键字:web config 重新启动 模拟 配置文件 我自己 自己的 | 更新日期: 2023-09-27 18:25:35

当您修改ASP.NET(MVC)应用程序的"web.config"文件时,该应用程序会自动重新编译/重新启动,从而强制读入修改后的"web.config"。

我的问题:

是否可以将这种更改检测行为应用于ASP.NET网站根目录中我自己的配置文件(比如"myconfig.json")?

也就是说,当有人修改"myconfig.json"文件时,应用程序就会重新启动。

可以为我自己的配置文件模拟web.config重新启动行为

您可以使用FileSystemWatcher监视文件并检测更改,然后重新启动应用程序或重新加载设置。

也许你不需要重新启动应用程序,只需要重新加载你的设置

protected void Application_Start()
{
    // Other initializations ...
    // ....
    var watcher = new FileSystemWatcher();
    //Set the folder to watch
    watcher.Path = Server.MapPath("~/Config");
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite;
    //Set a filter to watch
    watcher.Filter = "*.json";
    watcher.Changed += watcher_Changed;
    // Begin watching.
    watcher.EnableRaisingEvents = true;
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
    //Restart application here
    //Or Reload your settings
}