FileSystemWatcher无法正常工作 [英] FileSystemWatcher is not working

查看:104
本文介绍了FileSystemWatcher无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样在Form1_Load中添加了FileSystemWatcher:

I added FileSystemWatcher in Form1_Load like this:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ....................
        Dim watcher As New FileSystemWatcher()
        'For watching current directory
        watcher.Path = "/"
        'For watching status.txt for any changes
        watcher.Filter = "status.txt"
        watcher.NotifyFilter = NotifyFilters.LastWrite
        watcher.EnableRaisingEvents = True
        AddHandler watcher.Changed, AddressOf OnChanged
End Sub

我有一个OnChanged函数,它是一个简单的MessageBox.不过,当我更改status.txt文件时,没有显示任何消息框.

I have an OnChanged function which is a simple MessageBox. Still, when I change the status.txt file, no message box is shown.

推荐答案

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim watcher As New IO.FileSystemWatcher()

'For watching current directory
watcher.Path = **System.IO.Directory.GetCurrentDirectory()** 'Note how to obtain current directory
watcher.NotifyFilter = NotifyFilters.LastWrite

'When I pasted your code and created my own status.txt file using 
'right click->new->Text File on Windows 7 it appended a '.txt' automatically so the
'filter wasn't finding it as the file name was status.txt.txt renaming the file
'solved the problem
watcher.Filter = "status.txt" 

AddHandler watcher.Changed, AddressOf OnChanged

watcher.EnableRaisingEvents = True
End Sub

Private Shared Sub OnChanged(ByVal source As Object, ByVal e As IO.FileSystemEventArgs)
MessageBox.Show("Got it")
End Sub

来自 http://bartdesmet.net/blogs/bart/archive/2004/10/21/447.aspx

您可能会注意到,在某些情况下,单个创建事件会生成由您的组件处理的多个Created事件.例如,如果使用FileSystemWatcher组件监视目录中新文件的创建,然后使用记事本创建文件对其进行测试,则即使仅创建了一个文件,也可能会生成两个Created事件.这是因为记事本在写入过程中执行了多个文件系统操作.记事本分批写入磁盘,以创建文件内容,然后创建文件属性.其他应用程序可能以相同的方式执行.由于FileSystemWatcher监视操作系统的活动,因此将拾取这些应用程序触发的所有事件

You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use a FileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up

这篇关于FileSystemWatcher无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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