FileSystemWatcher in arraylist

Hi all,

I'm trying to monitor changes in a number of folders using FileSystemWatcher.

I have a procedure that accepts the path to monitor. A new FileSystemWatcher is created for that path, together with its event handlers, and added to an arraylist (watchList).

This seems to work fine, however I would like to be able to modify the attributes of specific watchers at run-time. I'm doing something like this to stop the first watcher in the arraylist:

Dim w As FileSystemWatcher
w = watchList.Item(0)
w.EnableRaisingEvents = False

This causes a NullReferenceException at the last line. In break mode I see the arraylist has 3 elements of type Object, but adding a watch for watchList.Item(0).path (or any other watcher property) gives a run-time exception.

Regards,

Mark




Answer this question

FileSystemWatcher in arraylist

  • Daggs

    Thanks for your help, Paul. You were right in suspecting the object in the array was null.

    I had forgotten to mention that the file monitoring was working correctly - it was when i tried to change properties that i got the exception, and that's what puzzled me.

    Anyway, the problem was a silly little oversight. My watcher creator is a function of type FileSystemWatcher. I forgot to put a return statement!

    return myWatch
    ' problem solved:)

    and that's why, kids, you have to practice every now and then or you'll get rusty.



  • Sameer Bhangar - MSFT

    Hi Mark,

    Your approach and code so far looks right.

    One problem you might have is that your procedure added a FileSystemWatcher object to the ArrayList, but that object was not successfully initialized. A simple example is if you create a FileSystemWatcher passing in a path that does not exist, e.g. "Dim w as FileSystemWatcher = new FileSystemWatcher("c:\pathdoesnotexist"). If you have no error handling then you will immediately hit an exception. If you do trap the exception, then w gets added to your ArrayList even though it is Null/Nothing.

    What you can do is protect against this situation by checking to see if your FileSystemWatcher object is Nothing before adding it to the ArrayList. It's also nice to trap any exceptions that happen when you create it.

    Here is a code sample that works for me:

    Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    'create 2 file system watchers

    Me.CreateWatcherForPath("C:\Windows\")

    Me.CreateWatcherForPath("C:\Temp\")

    '--now watchlist has 2 items

    'test changing properties

    Dim w As IO.FileSystemWatcher

    w = Me.watchList(0)

    w.Path = "c:\other\"

    w.EnableRaisingEvents = False

    Stop

    End Sub

    Friend watchList As New ArrayList

    Private Sub CreateWatcherForPath(ByVal path As String)

    'create new FileSystemWatcher object with defaults

    Dim fsw As IO.FileSystemWatcher

    Try

    fsw = New IO.FileSystemWatcher(path)

    fsw.EnableRaisingEvents = True

    Catch ex As Exception

    My.Application.Log.WriteEntry("Could not create FSW for path: " & path)

    End Try

    'check for null in case the FSW could not initialize

    If fsw IsNot Nothing Then

    'add it to the ArrayList; watchList.Count increases by 1

    Me.watchList.Add(fsw)

    End If

    End Sub

    Private Sub FileSystemWatcher1_Changed(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed

    Debug.WriteLine("fs1 changed: " & e.Name)

    End Sub

    End Class

    Hope this helps.

    Best,

    Paul Yuknewicz

    VB Program Manager


  • Brandon Bray

    You bet. I'm glad you uncovered the problem.

    One note is that you should see a Green squiggly / compiler warning in VB 2005 if you forget to have a Return in a function. This might help in the future - we all forget these things sometimes.


  • Jacob Christ

    Followed the example and I seend to have everything working (on the array side)

     

    The problem is my script isn't tracking any events. Nothing is being triggered

     

     

    'Get Sources button events
    Private Sub btnGetSources_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetSources.Click

    Call getsources()

    End Sub

     

    Public Sub getsources()

    conSQL.Open()

    cmdGetSources.CommandText = "SELECT * FROM Sources"
    drSources = cmdGetSources.ExecuteReader()

    With drSources

    if .HasRows Then

    While .Read
    ListBox1.Items.Add(.Item(1))
    createwatchers(.Item(1))
    End While

    End If

    End With

    drSources.Close()

    conSQL.Close()

    End Sub

     

    Private Sub createwatchers(ByVal e As String)

    'http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=224039&SiteId=1

    Dim fsw_watcher As FileSystemWatcher

    'Create filesystemwatcher and set property values.

    Try

    fsw_watcher = New FileSystemWatcher(e)
    fsw_watcher.IncludeSubdirectories = True
    fsw_watcher.EnableRaisingEvents = True
    fsw_watcher.NotifyFilter = NotifyFilters.FileName & NotifyFilters.DirectoryName

    Catch ex As Exception

    MessageBox.Show("Error occured, check application log")
    My.Application.Log.WriteEntry("QVBServ Could not create a FileSystemWatcher for path: " & e & ". Directory Doesn't Exist")

    End Try

    If fsw_watcher IsNot Nothing Then

    'add it to the ArrayList; watchList.Count increases by 1
    watcherArray.Add(fsw_watcher)
    fswCount.Text = watcherArray.Count
    'Dim arraytype As String = watcherArray.GetType.ToString()

    End If

    End Sub

     

     

    Private Sub FileSystemWatcher1_Changed(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed

    lbfileresults.Items.Add(e.Name & " " & e.ChangeType)

    End Sub

     

    Private Sub fsw_watcher_Changed(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles fsw_watcher.Changed

    lbfileresults.Items.Add(e.Name & " " & e.ChangeType)

    End Sub

    Forgive the formatting, couldn't find the codeblock tag


  • FileSystemWatcher in arraylist