Working with FileSystemWatcher and IOException Class using VB.NET

In this article I will explain you about FileSystemWatcher and IOException Class in VB.NET.
  • 3938

Another very useful class, FileSystemWatcher, acts as a watchdog for file system changes and raises an event when a change occurs. You must specify a directory to be monitored. The class can monitor changes to subdirectories and files within the specified directory. If you have Windows 2000, you can even monitor a remote system for changes. (Only remote machines running Windows NT or Windows 2000 are supported at present.)
 
The option to monitor files with specific extensions can be set using the Filter property of the FileSystemWatcher class. You can also fine-tune FileSystemWatcher to monitor any change in file Attributes, LastAccess, LastWrite, Security, and Size data.

The FileSystemWatcher class raises the events described below.

FileSystemWatcher events

Event Name Use
Changed Fired when a file or directory in the watched path is changed
Created Fired when a file or directory in the watched path is created
Deleted Fired when a file or directory in the watched path is deleted
Error Fired when the internal buffer overflows due to many changes made over a  short time, particularly when the buffer size is small
Renamed Fired when a file or directory in the watched path is renamed

Below code  Illustrates the use of the FileSystemWatcher class to capture changes to files and directories and report them on the console screen.

 Using the FileSystemWatcher Class

Imports
System.IO 
Public Class FileWatcher
    Public Shared Sub Main(ByVal args As String())
        ' If a directory is not specified, exit program.
        If args.Length <> 1 Then
            ' Display the proper way to call the program.
            Console.WriteLine("Usage: FileWatcher.exe <directory>")
            Console.WriteLine("Press any key to continue")
            Console.ReadLine()
            Return
        End If
        Try
            ' Create a new FileSystemWatcher and set its properties.
            Dim watcher As New FileSystemWatcher()
            watcher.Path = args(0)
             ' Watch both files and subdirectories.
            watcher.IncludeSubdirectories = True
            ' Watch for all changes specified in the NotifyFilters
            'enumeration.
            watcher.NotifyFilter = NotifyFilters.Attributes Or NotifyFilters.CreationTime Or
            NotifyFilters.DirectoryName Or NotifyFilters.FileName Or NotifyFilters.LastAccess Or
           
NotifyFilters.LastWrite Or NotifyFilters.Security Or NotifyFilters.Size 
            ' Watch all files.
            watcher.Filter = "*.*"
 
            ' Add event handlers.
            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) 
            'Start monitoring.
            watcher.EnableRaisingEvents = True
 
            'Do some changes now to the directory.
            'Create a DirectoryInfo object.
            Dim d1 As New DirectoryInfo(args(0))
            'Create a new subdirectory.
            d1.CreateSubdirectory("mydir"
            'Create some subdirectories.
            d1.CreateSubdirectory("mydir1\mydir2\mydir3")
            'Move the subdirectory "mydir3 " to "mydir\mydir3"
            Directory.Move(d1.FullName & "\mydir1\mydir2\mydir3", d1.FullName & "\mydir\mydir3"
            'Check if subdirectory "mydir1" exists.
            If Directory.Exists(d1.FullName & "\mydir1") Then
                'Delete the directory "mydir1"
                'I have also passed 'true' to allow recursive deletion of
                'any subdirectories or files in the directory "mydir1"
                Directory.Delete(d1.FullName & "\mydir1", True)
            End If
 
            'Get an array of all directories in the given path.
            Dim d2 As DirectoryInfo() = d1.GetDirectories() 
            'Iterate over all directories in the d2 array.
            For Each d As DirectoryInfo In d2
                If d.Name = "mydir" Then
                    'If "mydir" directory is found then delete it recursively.
                    Directory.Delete(d.FullName, True)
                End If
            Nex
 
            ' Wait for user to quit program.
            Console.WriteLine("Press 'q' to quit the sample.")
            Console.WriteLine() 
            'Make an infinite loop till 'q' is pressed.
            While Console.Read() <> "q"
            End While
       Catch e As IOException
            Console.WriteLine("A Exception Occurred :" & Convert.ToString(e))
         Catch oe As Exception
            Console.WriteLine("An Exception Occurred :" & Convert.ToString(oe))
        End Try
        Console.ReadLine()
    End Sub
 
    ' Define the event handlers.
    Public Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
        ' Specify what is done when a file is changed.
        Console.WriteLine("{0}, with path {1} has been {2}", e.Name, e.FullPath, e.ChangeType)
    End Sub
 
    Public Shared Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
        ' Specify what is done when a file is renamed.
        Console.WriteLine(" {0} renamed to {1}", e.OldFullPath, e.FullPath)
    End Sub
End Class

The code starts with the parameter obtained from the user in the form of a path to a directory. Then it creates a FileSystemWatcher instance to monitor all changes in files and directories. Once the FileSystemWatcher is enabled, we are ready to make some changes. In this example, a file and few directories are created and later deleted. Figure 6.2 contains the output displayed on the console screen.

Output of the FileWatcher class

1.gif

As you can see, the FileSystemWatcher captured every change made. If you start Windows Explorer and browse the directory you have provided as the parameter, you will find that every change you make in Explorer is reflected in the console. Since input is obtained from the user, chances are high that invalid arguments could raise exceptions; therefore, all the file manipulation code is placed within the try-catch block.

IOException Class

The IOException class is the base class for exceptions under the System.IO namespace. All other exceptions under this namespace-DirectoryNotFoundException, EndOfStreamException, FileNotFoundException, and FileLoadException-derive from the IOException class. I/O operations deal with various resources like hard disk, floppy disk, and network sockets, which have a greater chance of failing. Therefore, you should always encapsulate your I/O code within the try catch block to intercept any exceptions that might occur.

Conclusion

Hope this article would have helped you in understanding FileSystemWatcher and IOException Class  in VB.NET.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.