A recent ASP.NET project that I am working on requires that the web application monitor a directory for new files, and if new files are found, process them in some way.
Unfortunately the application is not accessed through its web interface very often and as a result it cannot poll the directory when pages are requested, sessions are created, etc. The web interface is actually used mostly for configuration of the application.
We have decided to keep a FileSystemWatcher object alive by adding it to the ASP.NET application object. In the global.asax we do the following:
private FileSystemWatcher fsw;
protected void Application_Start(Object sender, EventArgs e)
{
string monitorPath = this.Context.Server.MapPath("incomming/");
Application.Add("watcher", new System.IO.FileSystemWatcher(monitorPath));
fsw = (FileSystemWatcher)Application["watcher"];
fsw.EnableRaisingEvents = true;
fsw.IncludeSubdirectories = false;
fsw.Changed += new System.IO.FileSystemEventHandler(fsw_Changed);
fsw.Created += new System.IO.FileSystemEventHandler(fsw_Created);
}
This seems to work so far. Whenever a new file is dropped into the incoming/ directory, the FileSystemWatcher events fire and we are able to process incoming files.
A colleague of mine said that he tried this on another web application and that events from the FileSystemWatcher stopped firing at some point. Has anyone run into any problems using the FileSystemWatcher this way from an ASP.NET application?