用FileSystemWatcher監(jiān)控作業(yè)

字號:

在.NET Framework中的System.IO命名空間包括FileSystemWatcher類。這個類提供監(jiān)控作業(yè)的目錄或文件的功能。如果你的應(yīng)用程序需要知道新文件是何時被加入指定目錄的或者文件是何時被刪除的,那么這個功能會很有用處。
    要使用FileSystemWatcher,首先要創(chuàng)建一個類的實(shí)例。
    Private dirWatcher As New System.IO.FileSystemWatcher()
    接下來,通過設(shè)置Path屬性設(shè)置FileSystemWatcher來監(jiān)控指定目錄??梢栽O(shè)置IncludeSubdirectories屬性監(jiān)控指定目錄下的所有子目錄。
    dirWatcher.Path = "C:\Temp"
    dirWatcher.IncludeSubdirectories = False
    Filter屬性指定目錄內(nèi)要監(jiān)控的文件。這個屬性接受通配符,所以所有的文本文件都可以通過將它設(shè)定為"*.txt"文件來監(jiān)控。指定特殊文件名后只會對那個文件起作用。
    dirWatcher.Filter = "*.txt"
    NotifyFilter屬性決定被監(jiān)控的指定文件的屬性。
    dirWatcher.NotifyFilter = System.IO.NotifyFilters.LastAccess
    Or _
    System.IO.NotifyFilters.LastWrite
    在設(shè)定FileSystemWatcher屬性后,添加事件處理器來捕獲事件,并確定它能夠激發(fā)事件。
    AddHandler dirWatcher.Created, AddressOf Me.OnCreation
    AddHandler dirWatcher.Changed, AddressOf Me.OnCreation
    dirWatcher.EnableRaisingEvents = True
    最后,添加一個新的子程序來處理事件。
    Public Shared Sub OnCreation(ByVal source As Object, _
    ByVale As System.IO.FileSystemEventArgs)
    Debug.WriteLine("file: " & e.FullPath
    & " " & e.ChangeType)
    End Sub