文件系统监控
我曾经遇到过一些应用程序,需要等待和处理某个特定目录中的文件-例如,将数据从文件导入到数据库中去的应用程序。数据文件可以从某个大型机上下载,或者被转移到某个输入目录中,该应用程序将它们导入到数据库中。你不用经常地轮询该目录检查是否有新文件,可以等待生成新文件的通知。你可以在Visual Basic 6.0中使用Win32 API来做到这一点,而在Visual Basic .NET中你可以使用.NET Framework类来做这项工作。但是在.NET中实施文件监控与在.NET中完成其他工作的方法更加一致,因此学习曲线是最小的。
你可以使用System.IO.FileSystemWatcher .NET类对文件系统进行监视。它提供了一些属性,允许你设置监控的路径,指定是对文件还是子目录层次的变化感兴趣。System.IO.FileSystemWatcher还允许你指定需要监控的文件名和文件类型(例如,*.xml是指监控所有XML文件的变化)。最后,你可以指定感兴趣的变化类型-例如,只对新建文件,文件属性的变化或文件大小的变化(请参阅清单2)感兴趣。
在你设置了监控内容后,你需要钩住用于感兴趣的各种事件的事件处理程序。FileSystemWatcher事件有Changed、Created、Deleted、Error和Renamed。要处理某个事件,首先你需要编写一个与FileSystemEventHandler代理相同声明的事件处理程序,然后将这个处理程序添加到FileSystemWatcher类中。这个基于代理的体系结构允许你为同一个事件添加多个处理程序,或者对于多个事件使用同一个处理程序-而你不能使用Visual Basic 6.0做到这一点。
'System.IO contains the
'file monitoring classes and types
Imports System.IO
Module Module1
Sub Main()
'FileSystemWatcher does the real work
Dim fw As New FileSystemWatcher()
'WaitForChangedResult is what you
'get back when a change occurs
Dim result As WaitForChangedResult
'set the path to monitor
fw.Path = "C:/WINNT/"
'tell it whether to watch files or directories
fw.Target = WatcherTarget.File
'tell it whether to include subdirs
fw.IncludeSubdirectories = False
'hook up handlers
AddHandler fw.Created, _
New FileSystemEventHandler(AddressOf OnFileNotify)
'enable the watcher
fw.Enabled = True
Do
Console.WriteLine("Beginning to monitor")
'this is where we actually wait
'waiting blocks execution for the specified timeout
result = fw.WaitForChanged(WatcherChangeTypes.All, 60000)
Console.WriteLine("Hit Enter to continue q to quit")
Loop While (Console.ReadLine <> "q")
End Sub
'This is the delegate that gets
'called when a file is created
Public Sub OnFileNotify(ByVal source As Object, _
ByVal e As FileSystemEventArgs)
Console.WriteLine( _
"Notification received for file {0}, change type is {1}", _
e.FullPath, e.ChangeType)
End Sub
End Module