如何在没有持续扫描的情况下检测目录或文件何时发生更改 [英] How do I detect when a directory or file changes without constant scanning

查看:23
本文介绍了如何在没有持续扫描的情况下检测目录或文件何时发生更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了读取所有文件并将它们与之前的快照进行比较之外,还有没有办法检测 C# 和 Windows 中的目录何时发生变化?如果需要的话,我不介意 PInvoke.

Other than reading all the files and comparing them with a previous snapshot, is there a way to detect when a directory changes in C# with Windows? I don't mind PInvoke if that's what it takes.

EDIT FileSystemWatcher 类很棒,但有一个问题是您必须将回调通知中的任何工作启动到后台任务/线程,以避免阻塞,这将导致丢弃事件.

EDIT The FileSystemWatcher class is great, but one gotcha is that you must kick off any work in the callback notification to a background task/thread to avoid blocking which will cause dropped events.

推荐答案

使用 FileSystemWatcher 类 - 它可以满足您的需求.它不会告诉您文件中的哪些字节发生了变化,但它会告诉您哪些文件发生了变化.

Use the FileSystemWatcher class - it does what you want. It won't tell you which bytes in the file changed, but it will tell you which files have changes.

来自文档:

使用 FileSystemWatcher 来监视指定目录中的更改.你可以观察文件的变化和指定的子目录目录.您可以创建一个组件要在本地计算机上观看文件,网络驱动器或远程计算机.

Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.

要监视所有文件中的更改,请设置Filter 属性为空字符串("") 或使用通配符 (".").到观看特定文件,设置过滤器属性到文件名.为了例如,观察变化文件 MyDoc.txt,设置过滤器属性为MyDoc.txt".你也可以观察某种类型的变化文件.例如,要注意文本文件的变化,设置过滤器属性为*.txt".

To watch for changes in all files, set the Filter property to an empty string ("") or use wildcards ("."). To watch a specific file, set the Filter property to the file name. For example, to watch for changes in the file MyDoc.txt, set the Filter property to "MyDoc.txt". You can also watch for changes in a certain type of file. For example, to watch for changes in text files, set the Filter property to "*.txt".

您可以进行多种类型的更改可以在目录或文件中观察.例如,您可以观察变化在属性中,LastWrite 日期和时间,或文件的大小或目录.这是通过设置完成的将 NotifyFilter 属性设置为以下之一NotifyFilters 值.更多有关您的更改类型的信息可以观看,请参阅 NotifyFilters.

There are several types of changes you can watch for in a directory or file. For example, you can watch for changes in Attributes, the LastWrite date and time, or the Size of files or directories. This is done by setting the NotifyFilter property to one of the NotifyFilters values. For more information on the type of changes you can watch, see NotifyFilters.

您可以监视重命名、删除、或创建文件或目录.例如,要注意重命名文本文件,将过滤器属性设置为"*.txt" 并调用 WaitForChanged指定了重命名的方法其参数.

You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the Filter property to "*.txt" and call the WaitForChanged method with a Renamed specified for its parameter.

这篇关于如何在没有持续扫描的情况下检测目录或文件何时发生更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆