如何在不定期扫描的情况下检测目录或文件何时更改 [英] How do I detect when a directory or file changes without constant scanning

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

问题描述

除了阅读所有文件并将其与先前的快照进行比较以外,有没有办法检测目录在Windows中的C#中何时更改?我不介意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.

推荐答案

使用 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.

从文档: / p>

From the doc:


使用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属性设置为空字符串
()或使用通配符()。要
观看特定文件,请将Filter
属性设置为文件名。对于
示例,要监视
文件MyDoc.txt中的更改,请将Filter
属性设置为MyDoc.txt。您还可以
监视某种类型的
文件中的更改。例如,要查看文本文件中的
更改,请将Filter
属性设置为* .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.

您可以观看重命名,删除,
或创建文件或目录。
例如,要监视
文本文件的重命名,请将Filter属性设置为
* .txt,并调用WaitForChanged
方法,并为$ b $指定的重命名b其参数。

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天全站免登陆