VB.NET • Start File Monitoring

Listing 1. Determine what type of item is listed in the TextBox, and set the FileSystemWatcher's Path and Filter properties appropriately, including subdirectory monitoring based on the CheckBox setting. Disable the controls in the GroupBox once monitoring begins so the user can't make settings changes. Next, set the NotifyFilter property to determine the types of changes you want to detect and start monitoring by setting the EnableRaisingEvents property to True.

Private Sub StartMonitor()
   If Directory.Exists(txtWatchPath.Text) Then
      'it's a directory
      FileSystemWatcher1.Path = txtWatchPath.Text
      FileSystemWatcher1.Filter = String.Empty
   ElseIf txtWatchPath.Text.Trim.Length > 0 _
      AndAlso Directory.Exists(Path. _
      GetDirectoryName(txtWatchPath.Text)) Then
      'it's a filespec
      FileSystemWatcher1.Path = _
         Path.GetDirectoryName( _
      FileSystemWatcher1.Filter = _
      StatusBar1.Text = "A valid path " & _
         "wasn't specified..."
      Exit Sub
   End If
   FileSystemWatcher1.IncludeSubdirectories = _
   grpMonitor.Enabled = False
   FileSystemWatcher1.NotifyFilter = _
      (NotifyFilters.CreationTime Or _
      NotifyFilters.LastWrite Or _
      NotifyFilters.FileName Or _
   FileSystemWatcher1.EnableRaisingEvents = True
   StatusBar1.Text = "Monitoring..."
End Sub