Delphi XE中如何监控目录中的文件?

发布于 2024-11-03 03:22:05 字数 226 浏览 5 评论 0原文

可能的重复:
文件更新时的 Delphi 通知

需要监视创建文件和计数他们。 操作系统:WinXP及以上。

Possible Duplicate:
Delphi notification when a file gets updated

Need monitoring for create files and count them.
OS: WinXP and high.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱已欠费 2024-11-10 03:22:05

去年我有同样的需求并尝试了 Iztok Kacin 的 Directory Watch。他回复了电子邮件并且对回答我的问题非常有帮助。

他的代码有效,但我需要在特定文件夹中的文件被关闭时得到通知,由于某种奇怪的原因,来自 Microsoft 的 ReadDirectoryChanges API(它所依赖的)(令人抓狂地)没有这样做不提供。我似乎还记得 Iztok 的代码使用了线程,感觉不够轻量,无法满足我的需求。

我最终使用了一种非常简单的方法,但对我来说效果非常好。在每隔几秒触发一次的 TTimer 事件中,我对正在监视的文件夹使用 FindFirst。找到的所有文件都放入持久的 TStringList 中。任何在以前的 TTimer 事件的 StringList 中找到的文件都是新文件。 (为了检测文件是否已关闭,我尝试以独占模式打开该文件。如果无法打开它,则它不会添加到 TStringList 中,因此会在下一个事件中检查它。)

我非常犹豫是否使用这个方法,认为这太暴力了。但是,对于我的需求,这个解决方案非常有效,值得庆幸的是,它涉及少量非常简单的代码,易于理解和维护。

华泰

Last year I had the same need and tried out Iztok Kacin's Directory Watch. He responded to email and was very helpful in answering my questions.

His code worked, but I needed to be notified at the moment a file in a specific folder was closed, which for some odd reason, the ReadDirectoryChanges API (on which it depends) from Microsoft (maddeningly) doesn't provide. I also seem to recall that Iztok's code used threads and didn't feel light-weight enough for my needs.

I ended up using a surprisingly simple approach that has worked wonderfully for me. On a TTimer event that fires every few seconds, I use FindFirst on the folder I'm monitoring. All files found are put in a persistent TStringList. Any file that is found that isn't already in the StringList from previous TTimer events is new. (To detect if a file is closed, I try to open the file in exclusive mode. If I can't open it, then it's not added to the TStringList so it's checked on the next event.)

I was quite hesitant to use this approach, thinking it was far too brute-force. But, for the needs I had, this solution has worked out wonderfully and thankfully, involves a small amount of very simple code that is easy to understand and maintain.

HTH

酒几许 2024-11-10 03:22:05

您可能想看看这篇文章(Delphi 的目录监视器类) ,以及来自 Windows API 的此函数: ReadDirectoryChanges

您还应该看看这个问题,因为它可能适合您的需求:文件更新时的 Delphi 通知

You may want to take a look at this article (A Directory Monitor Class For Delphi), and also at this function from Windows API: ReadDirectoryChanges

You should also take a look at this SO question since it may suit your needs: Delphi notification when a file gets updated

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文