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
1private FileSystemWatcher _fsw;
2
3protected void Application_Start(object sender, EventArgs e)
4{
5 string monitorPath = Server.MapPath("");
6
7 Application.Add("fileWatcher", new FileSystemWatcher(monitorPath));
8 _fsw = (FileSystemWatcher)Application["fileWatcher"];
9 _fsw.EnableRaisingEvents = true;
10
11 _fsw.Changed += OnWatchFileChanged;
12}
13
14protected void Application_End(object sender, EventArgs e)
15{
16 FileSystemWatcher fileWatcher = (FileSystemWatcher)Application["fileWatcher"];
17 Application.Remove("fileWatcher");
18 fileWatcher.Dispose();
19}
20
21private void OnWatchFileChanged(object source, FileSystemEventArgs e)
22{
23 // Do required stuff
24 string requiredstuff = "";
25}