I’m looking for a good solution to constantly read files within a directory in my windows service. Currently, I’m using FileSystemWatcher to process xml files that get added to the directory.This works well when the service is running. However, if the services gets stopped for whatever reason, the files that were added to the directory while the service was stopped never get processed. What’s the best possible solution? Below is the code I have for FileSystemWatcher. Maybe FileSystemWatcher can do this, however, I could be using it incorrectly.
// Setup FileSystemWatcher to watch 'IN' directory...
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = ConfigurationManager.AppSettings["InputPath"];
watcher.EnableRaisingEvents = true;
watcher.Filter = "*.xml";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(FileAdded);
You’re stating two different use cases – startup and monitoring.
The FileSystemWatcher is simply for monitoring.
But on startup, you have to look into the filesystem itself, see if there are any files waiting, and if so, deal with them. Ideally, you should be able to use your FileAdded function, or at least have FileAdded call the same function to process the file.
On startup, I would do a simple loop:
while (there are any files in InputPath)
{
process a file();
}
add the FileSystemEventHandler code;