文件系统监控

 
文件系统监控


我曾经遇到过一些应用程序,需要等待和处理某个特定目录中的文件-例如,将数据从文件导入到数据库中去的应用程序。数据文件可以从某个大型机上下载,或者被转移到某个输入目录中,该应用程序将它们导入到数据库中。你不用经常地轮询该目录检查是否有新文件,可以等待生成新文件的通知。你可以在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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值