Windows Service - FileSystemWatcher

  • Thread starter Thread starter Nick K.
  • Start date Start date
N

Nick K.

I'm trying to implement a FileSystemWatcher from a Windows Service.
Everything works until I:

Stop the Service
Copy a file to the watched directory.
Re-Start the Service.

I would expect the watched directory, which has a file in it to start
processing, but it does not. Is there some trick to this?
 
Nick,

When you stop your service, are you shutting down your instance of the
file system watcher? I would think that if this is the case, then that's
what should happen.

The file system watcher is good only for watching events as they happen,
not for determining what files are currently changing.

If you want that behavior, then you will have to create a list of files
that are in the directory when the service shuts down. On restart, you have
to iterate through the list, and then find out what files changed, and then
process them accordingly.

Hope this helps.
 
The FileSystemWatcher looks only for files created while it is
instantiated, not files created since it last existed. If the directory
were to contain a mix of processed and unprocessed files, how would the
watcher know which ones had been created since it last ran?

When your service starts up, it must create the FileSystemWatcher, then
process all files already in the directory.

Here, we use renaming to make the whole thing work smoothly. Producer
programs create the file in the target directory with a .tmp suffix,
then rename them to their permanent names after the file is completed
and closed. The FileSystemWatcher then notices the file and picks it up
for processing.

As soon as the consumer finishes processing the file, it either deletes
it or renames it with a .done extension, or something like that.

That way if the service ever crashes and restarts, it can always find
all of the appropriately named files and start processing them right
away, secure in the knowledge that none of them are half-built, and
none of them has completed processing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top