Filewatcher in global.asax.

I needed to watch for files changing in the root of my site. Specifically I was doing this as I had an XML file with all my routing information defined. So if this XML file changed I needed to reload the routes and add all the changes.

You can do this by using the FileSystemWatcher Class and adding it to the System.Web.HttpApplication within your Global.asax.

The Code

private FileSystemWatcher _fsw;

protected void Application_Start(object sender, EventArgs e)
{
	string monitorPath = Server.MapPath("");

	Application.Add("fileWatcher", new FileSystemWatcher(monitorPath));
	_fsw = (FileSystemWatcher)Application["fileWatcher"];
	_fsw.EnableRaisingEvents = true;

	_fsw.Changed += OnWatchFileChanged;
}

protected void Application_End(object sender, EventArgs e)
{
	FileSystemWatcher fileWatcher = (FileSystemWatcher)Application["fileWatcher"];
	Application.Remove("fileWatcher");
	fileWatcher.Dispose();
}

private void OnWatchFileChanged(object source, FileSystemEventArgs e)
{
	// Do required stuff
	string requiredstuff = "";
}