Watching the FileSystem

Inspired by a blog entry by The Powershell Guy.

This code example watches the filesystem using System.IO.FileWatcher. It notifies you of changes via a callback: from System.IO import FileSystemWatcher from System.Threading import Thread

watcher = FileSystemWatcher watcher.Path = 'c:\\Temp'

def onChanged(source, event): print 'Changed:', event.ChangeType, event.FullPath

def onRenamed(source, event): print 'Renamed:', event.OldFullPath, event.FullPath

watcher.Changed += onChanged watcher.Created += onChanged watcher.Deleted += onChanged watcher.Renamed += onRenamed

watcher.EnableRaisingEvents = True

Thread.Sleep(60 * 1000 * 60)
 * 1) wait for an hour

You will see output like: Renamed: c:\Temp\wobble c:\Temp\3 Changed: Deleted c:\Temp\3 Changed: Deleted c:\Temp\fish

NOTES: The events are raised on another thread. The Changed event is raised when changes are made to the size, system attributes, last write time, last access time, or security permissions of a file or directory in the directory being monitored. Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised.

If you want to include subdirectories of a directory you are watching, you can set the IncludeSubdirectories property to True...

By default a FileSystemWatcher watches for any changes in a directory. If you only want to watch an individual file, or files with specific extensions, then you need to use the Filter Property. The following code will only watch for changes in a file called 'data.txt': from System.Threading import Thread

watcher = FileSystemWatcher watcher.Path = 'c:\\Temp' watcher.Filter = 'data.txt'

The next example watches for changes in any text files: from System.Threading import Thread

watcher = FileSystemWatcher watcher.Path = 'c:\\Temp' watcher.Filter = '*.txt'

Back to Contents.