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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| 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 = "";
}
|