有的时候需要在新建、修改和删除文件时执行一些操作,这就需要监控文件的变更。http://zhanyonhu.blog.163.com/blog/static/16186044200882484143208/提出了3种方法来实现:
1. 函数FindFirstChangeNotification和FindNextChangeNotification
2. 系统核心工具软件,比如FileMon(文件监视),开放源代码
3. Hook API,钩住CreateFile函数,分析其参数,借此来判断是创建文件还是读写文件;钩住DeleteFile函数,监视文件删除操作;钩住CreateDirectory和RemoveDirectory,借此判断是否是删除文件;钩住回收站相关函数,借此判断是否是移动到回收站。
后面两种方法一个使用驱动相关的技术,一个使用Hook,都比较复杂。通过Windows提供的API已经可以满足一些基本的文件监控需求。下面主要看下2个函数:
FindFirstChangeNotification Function
Creates a change notification handle and sets up initial change notification filter conditions. A wait on a notification handle succeeds when a change matching the filter conditions occurs in the specified directory or subtree. The function does not report changes to the specified directory itself.
This function does not indicate the change that satisfied the wait condition. To retrieve information about the specific change as part of the notification, use the ReadDirectoryChangesW function.
HANDLE WINAPI FindFirstChangeNotification(
__in LPCTSTR lpPathName,
__in BOOL bWatchSubtree,
__in DWORD dwNotifyFilter
);
Parameters
lpPathName
The path of the directory to be watched.
In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\