如何在不不断扫描的情况下检测目录或文件何时发生更改
除了读取所有文件并将它们与以前的快照进行比较之外,有没有办法在 Windows 中的 C# 中检测目录何时发生更改?如果需要的话,我不介意 PInvoke。
编辑 FileSystemWatcher 类很棒,但有一个问题是您必须启动后台任务/线程的回调通知中的所有工作,以避免阻塞,从而导致事件丢失。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 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.
From the doc:
我必须为一个程序执行此操作,该程序将监视目录并查看是否添加了任何新图像文件,然后它会自动调整它们的大小。当有人一次添加多个文件时,观察者不会捕获所有文件,因为它是单线程的,并且在删除另一个图像的同时忙于调整一个图像的大小。
我必须使其成为一个多线程应用程序,其中主线程仅监视目录并将文件添加到队列中,另一个线程将从队列中读取并调整这些图像的大小。
如果您要对这些文件执行任何操作,则可能需要小心这一点。
I've had to do this for a program that would watch a directory and see if any new image files were added, and it would then automatically resize them. When someone would add multiple files at one time, the watcher wouldn't catch all the files since it was single threaded and was busy resizing one image while another was being dropped.
I had to make this a multi-threaded app, where the main thread just watched the directory and added the files to a queue, and another thread would read from the queue and resize those images.
That's something you might want to be careful of if you're going to be doing anything with the files.