How do I monitor a file directory for added/deleted/ changed files?

Event Gateways: Directory Watcher

Open the ColdFusion Administrator and go to "EVENT GATEWAYS/Gateway Types". ColdFusion comes with a few predefined Gateway Types one of them being "DirectoryWatcher".

Now select "Gateway Instances" under the "EVENT GATEWAYS" heading in the left-hand menu. Create a new directory somewhere on your server to host the CFC and Configuration files that will handle your new Gateway operation.

For example: C:\Inetpub\wwwroot\com\company\services\dw

1. Inside this folder, create a new CFC (watch_dir.cfc) with the following contents:

<cfcomponent>
<cffunction name="onAdd" returntype="any">
<cfargument name="CFEvent" type="struct" required="yes">
<cfset data = CFEvent.data>
<cffile action="append" file="C:\Inetpub\wwwroot\com\company\services\dw\eventdata.txt" output="#data#">
</cffunction>
</cfcomponent>

2. Create another file (watch_dir.cfg) with the following contents (hash/pound signs and all):

#
# DirectoryWatcherGateway configuration file
#
# The directory you want to watch. If you are entering a Windows path
# either use forward slashes (C:/mydir) or escape the back slashes (C:\\mydir). directory=C:\\MY_DIRECTORY
# Should we watch the directory and all subdirectories too
# Default is no. Set to 'yes' to do the recursion. 
recurse=yes
# The interval between checks, in milliseconds
# Default is 10 seconds
interval=10000
# The comma separated list of extensions to match.
# Default is * - all files
extensions=*
# CFC Function for file Change events
# Default is onChange, set to nothing if you don't want to see these events
#changeFunction=
# CFC Function for file Add events
# Default is onAdd, set to nothing if you don't want to see these events
addFunction=onAdd
# CFC Function for file Delete events
# Default is onDelete, set to nothing if you don't want to see these events
#deleteFunction=

For this example, we are only using the onAdd method.

Specify the following criteria for your new "Gateway Instance":

Gateway ID: watchInboundFiles

Gateway Type: DirectoryWatcher - Watches a directory for file changes (Select)

*CFC Path: C:\Inetpub\wwwroot\com\company\services\dw\watch_dir.cfc

*Configuration File: C:\Inetpub\wwwroot\com\company\services\dw\watch_dir.cfg

Startup Mode: Automatic (Select)

Click "Add Gateway Instance".

Under "Configured ColdFusion Event Gateway Instances", Start you Instance.

Now drop a new file in your "C:\MY_DIRECTORY" and open the "eventdata.txt" to see some variables added. You can now modify the "watch_dir.cfc" to handle these results in any way you like.

Be sure to check the "Debugging & Logging/Log Files: eventgateway.log" if things doesn't work as expected. It usually has some useful debugging information if something went wrong.

This question was written by Stefan le Roux
It was last updated on July 21, 2008.

Categories

File and Directory Access

Comments

comments powered by Disqus