检测新创建的文件、刚刚编辑的文件
我试图在编辑或创建发生时及时读取文件。还有另一个硬件可以将文件创建到我希望访问(及时)的文件夹中。
如何使用 C# .net 检测新编辑或创建的文件的创建。我不想定期轮询文件夹,因为机器可能会在轮询时间间隔之间写入多次。即我想避免:
- 文件 1(创建) 10:00:04AM
- 轮询文件 1(无数据丢失) 10:00:05AM
- 文件 1(用新数据覆盖) 10:00:07AM
- 轮询文件 1(无数据丢失) 10:00:10AM
- 文件 1(用新数据覆盖) 10:00:12AM
- 文件 1(用新数据覆盖) 10:00:14AM
- 轮询文件 1(10:00:12AM 数据丢失) 10:00:15AM
I am trying to read a file on a timely basis the moment an edit or creation occurs. There is another piece of hardware that creates files to a folder which i wish to access (on a timely basis).
How does one go about detecting the creation a newly edited or created file using C# .net. I do not want to poll the folder on a periodic basis as the machine could potentially write several times in between the polling time interval. i.e. I want to avoid:
- File 1 (created) 10:00:04AM
- Poll file 1 ( no data lost ) 10:00:05AM
- File 1 (overwritten with new data) 10:00:07AM
- Poll File 1 ( no data lost ) 10:00:10AM
- File 1 (overwritten with new data) 10:00:12AM
- File 1 (overwritten with new data) 10:00:14AM
- Poll File 1 ( 10:00:12AM data lost) 10:00:15AM
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
很简单,使用 FileSystemWatcher。
It's simple, use FileSystemWatcher.
我认为 FileSystemWatcher 类会给你你想要的正在寻找。
I think the FileSystemWatcher class will give you what you're looking for.
您可以使用 FileSystemWatcher 类。它允许您监视特定目录(您还可以对文件类型应用过滤器),如果文件发生更改,则会引发事件。
有来自 msdn 的示例代码:
这里
OnChanged
和OnRenamed
是具有您的逻辑的事件处理程序。You can use FileSystemWatcher class. It allows you to watch specific directory (you can also apply filter for a file type) and if the file is changed the event will be raised.
Here you have sample code from msdn:
where
OnChanged
andOnRenamed
are events handlers with your logic.