Implementation of the File SystemWatcher class

The following code example shows the implementation of FileSystemWatcher class in Visual Basic and C#. The code example shows the implementation of the FileSystemWatcher class to monitor the root of the C drive for new and modified files. The RenamedEventHandler delegate handles events that occur when the user renames a file or folder in the C drive. The ErrorEventHandler delegate handles events when an error occurs while creating, modifying, renaming, or deleting a file or folder in the C drive. The RenamedEventArgs class passes the arguments that display the old full path, old name, and the new name of the file or folder that is renamed. The ErrorEventArgs class displays an error message when an error occurs while managing files or folders in the C drive. When a new or an updated file is detected, information about the file is displayed at the console.

Visual Basic

Sub Main()

Dim watcher As FileSystemWatcher = New FileSystemWatcher("C:\")

watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)

AddHandler watcher.Changed, New FileSystemEventHandler(AddressOf OnChanged)

AddHandler watcher.Created, New FileSystemEventHandler(AddressOf OnChanged)

AddHandler watcher.Deleted, New FileSystemEventHandler(AddressOf OnChanged)

AddHandler watcher.Renamed, New RenamedEventHandler(AddressOf OnRenamed)

AddHandler watcher.Error, New ErrorEventHandler(AddressOf OnError)

watcher.EnableRaisingEvents = True

Console.WriteLine("Press 'Enter' to exit...") Consol e. ReadLine() End Sub

Private Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs) Dim changeType As WatcherChangeTypes = e.ChangeType

Console.WriteLine("The file {0} {1}", e.FullPath, changeType.ToString()) End Sub

Private Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs) Dim changeType As WatcherChangeTypes = e.ChangeType

Console.WriteLi ne("The file {0} {2} to {1}", e.OldFullPath, e.FullPath, changeType.ToString()) End Sub

Private Sub OnError(ByVal source As Object, ByVal e As ErrorEventArgs)

Console.WriteLine("An error has occurred.") End Sub

Was this article helpful?

0 0

Post a comment