Broken links? Email us! |
8 users have rated this article. result: |
|
5 out of 5. |
|
Download source files - 10 Kb
Download demo project - 33 Kb
Introduction
This code wraps up the Win32 API function ReadDirectoryChangesW so that your application only has to worry about responding to the events that take place when a file or directory is added, removed, modified or renamed.
This code will only work on Windows NT or Windows 2000, and the directory you wish to watch must also reside on a Windows NT or Windows 2000 computer.
There are two classes that must be used together to watch a directory, they are:
CDirectoryChangeWatcher and CDirectoryChangeHandler.
The public interface of CDirectoryChangeWatcher:
class CDirectoryChangeWatcher{
public:
CDirectoryChangeWatcher();
virtual ~CDirectoryChangeWatcher();
DWORD WatchDirectory(const CString & szDirToWatch,
DWORD dwChangesToWatchFor,
CDirectoryChangeHandler * pChangeHandler,
BOOL bWatchSubDirs = FALSE);
BOOL IsWatchingDirectory(const CString & strDirName);
BOOL UnwatchDirectory(const CString & szDirToStopWatching);
BOOL UnwatchAllDirectories();
...
};
The class CDirectoryChangeHandler has the following interface:
class CDirectoryChangeHandler{
public:
CDirectoryChangeHandler();
virtual ~CDirectoryChangeHandler();
...
BOOL UnwatchDirectory();
CString GetChangedDirectoryName();
protected:
virtual void On_FileAdded(const CString & strFileName);
virtual void On_FileRemoved(const CString & strFileName);
virtual void On_FileModified(const CString & strFileName);
virtual void On_FileNameChanged(const CString & strOldFileName,
const CString & strNewFileName);
virtual void On_ReadDirectoryChangesError(DWORD dwError);
To handle the events that happen when a file or directory is added, deleted, modified, or renamed, create a class derived from CDirectoryChangeHandler that does all of the things that you want to do when these events happen.
class CMyDirectoryChangeHandler : public CDirectoryChangeHandler{...};
To watch a directory call CDirectoryChangeWatcher::WatchDirectory();
Example:
m_DirectoryWatcher.WatchDirectory(_T("C:\Temp"),
FILE_CHANGE_NOTIFY_CREATION ,
&m;_MyChangeHandler);
As files are changed, renamed, etc. The appropriate CDirectoryChangeHandler::OnFilexxx() function will be called.
A single instance of CDirectoryChangeWatcher can be used to watch multiple directories at the same time. It is also possible to use a different CDirectoryChangeHandler for each watched directory, or to use the same CDirectoryChangeHandler for any # of watched directories.
CDirectoryChangeWatcher was based on the FWatch example program in the SDK and uses an io completion port so that there will always be only one worker thread for any # of watched directories.
Download the sample program for more details.
Feel free to email me with bugs, bug fixes, tips, comments, accolades or admonitions at wesj@hotmail.com.
|
| | Author | |
| | Date | |
| | -- No entries present -- | |
|