Windows文件变更监控

有的时候需要在新建、修改和删除文件时执行一些操作,这就需要监控文件的变更。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 "\

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
FileSystemWatcher是一个.NET框架提供的用于监控文件系统变更的组件。通过FileSystemWatcher,我们可以在文件发生变化时进行相应的处理,例如拷贝、删除、移动等等。使用FileSystemWatcher,我们可以在Windows监控文件夹、文件以及网络共享的文件系统变更。 FileSystemWatcher为我们提供了多种事件来观察文件系统变更的细节。当文件夹、文件或网络共享上的文件发生变更时,FileSystemWatcher会触发相应的事件。事件列表包括Changed、Created、Deleted、Renamed。对于每个事件,我们可以通过FileSystemEventArgs对象来获得发生变更文件名、路径、类型等信息。 在使用FileSystemWatcher之前,我们需要确定监控的路径和需要处理的事件类型。如果要监控多个路径,可以使用多个FileSystemWatcher实例来进行处理。需要注意的是,FileSystemWatcher可能会发生一些意外的错误,例如监控文件的时候文件正在被修改,或者文件已被删除,此时我们需要采取合适的方法来处理这些错误。我们也可以调整FileSystemWatcher的属性来控制监控的精度和延迟等参数,从而更好地适应应用场景。 总之,使用FileSystemWatcher可以方便地监控文件系统变更,从而更好地实现文件系统管理。例如,在文件复制或移动的过程中,我们可以使用FileSystemWatcher来监控是否成功地复制或移动文件。同时,对于进行监控的路径和事件类型,我们可以根据实际情况进行调整和优化,从而更好地适用于不同的应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值