2

When you modify the "web.config" file of an ASP.NET (MVC) application, the application is automatically recompiled/restarted, forcing the modified "web.config" to be read-in.

My question:

Is it possible to apply this change-detection behaviour for my own configuration files (let's say "my-config.json") in the root of an ASP.NET website?

I.e. when someone modifies the "my-config.json" file, the application gets restarted.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 1
    You can have a [`FileSystemWatcher`](https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx) to watch your files and detect changes and then restart application. – Reza Aghaei Dec 04 '15 at 13:08
  • @RezaAghaei Nice idea. It seems that there are only [undocumented ways](http://blog.diniscruz.com/2013/04/how-to-restart-iis-worker-process.html) to restart an ASP.NET application? – Uwe Keim Dec 04 '15 at 13:16
  • 1
    There are some answers in SO about restarting the application, for example: [Restarting (Recycling) an Application Pool](http://stackoverflow.com/questions/249927/restarting-recycling-an-application-pool), Also you can restart using – Reza Aghaei Dec 04 '15 at 13:32
  • 2
    Maybe you don't need to restart the application, and you only need to reload your settings. – Reza Aghaei Dec 04 '15 at 13:35

1 Answers1

2

You can have a FileSystemWatcher to watch your files and detect changes and then restart application or reload your settings.

Maybe you don't need to restart the application, and you only need to reload your settings

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
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398