Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Dynamic FileSystemWatcher listview error when adding

$
0
0
I am trying to make a filesystemwathcer that monitors all of the users drives

First declaring the control that will store the letters
Dim lstFiles As New ListBox



Second getting the drives:
        For Each drive_info As DriveInfo In DriveInfo.GetDrives()
            lstFiles.Items.Add(drive_info.Name)
        Next drive_info




After that make the filesystemwathcers for each drive:
  Try
            Dim arrFSW() As FileSystemWatcher
            ReDim arrFSW(lstFiles.Items.Count - 1)
            For i As Integer = 0 To lstFiles.Items.Count - 1
                ' strFile = lstFiles.Items(i)
                arrFSW(i) = New FileSystemWatcher
                arrFSW(i).Path = lstFiles.Items.Item(i).ToString
                arrFSW(i).Filter = "*.*"
                arrFSW(i).NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)
                arrFSW(i).IncludeSubdirectories = True
                AddHandler arrFSW(i).Changed, AddressOf FSWChanged
                AddHandler arrFSW(i).Deleted, AddressOf FSWDeleted
                AddHandler arrFSW(i).Renamed, AddressOf FSWRenamed
                arrFSW(i).EnableRaisingEvents = True
            Next
        Catch ex As Exception
            'drives that are invalid/without files
        End Try


Here comes the problem
Add each handler i made them to add the information to 'listview1'
    Public Sub FSWChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
        ListView1.Items.Add("File changed: " & e.FullPath.ToString & " change type: " & e.ChangeType)
    End Sub
    Public Sub FSWDeleted(ByVal source As Object, ByVal e As FileSystemEventArgs)
       ListView1.Items.Add("File: " & e.Name.ToString & " deleted")
    End Sub
    Public Sub FSWRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
         ListView1.Items.Add("File renamed from: " & e.OldName.ToString & " to: " & e.Name.ToString)
    End Sub


But i get the error:

Quote

Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on.

Viewing all articles
Browse latest Browse all 51036

Trending Articles