Guys,
I have an application that used to run just fine on .NET 2.0 but now that I'm trying to migrate it to .NET 3.5 I'm getting this error:
Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.
Here is the code:
Code:
Imports System.IO
Imports System.Diagnostics
PublicClass Form1
Public watchFolder As FileSystemWatcher
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
watchFolder = New System.IO.FileSystemWatcher()
'Path and file type
watchFolder.Path = "C:\XML\"
watchFolder.Filter = "*.XML"
'Filters
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or IO.NotifyFilters.FileName Or NotifyFilters.Attributes Or NotifyFilters.DirectoryName
' Event Handlers
AddHandler watchFolder.Changed, AddressOf fileChange
AddHandler watchFolder.Created, AddressOf fileChange
AddHandler watchFolder.Deleted, AddressOf fileChange
AddHandler watchFolder.Renamed, AddressOf fileRename
watchfolder.EnableRaisingEvents = True
Button1.Enabled = False
Button2.Enabled = True
EndSub
PrivateSub fileChange(ByVal source AsObject, ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
TextBox1.Text &= "File " & e.FullPath & " has been modified" & vbCrLf
EndIf
If e.ChangeType = IO.WatcherChangeTypes.Created Then
TextBox1.Text &= "File " & e.FullPath & " has been created" & vbCrLf
EndIf
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
TextBox1.Text &= "File " & e.FullPath & " has been deleted" & vbCrLf
EndIf
EndSub
PublicSub fileRename(ByVal source AsObject, ByVal e As System.IO.RenamedEventArgs)
TextBox1.Text &= "File" & e.OldName & " has been renamed to " & e.Name & vbCrLf
EndSub
PrivateSub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' Stop watching the folder
watchfolder.EnableRaisingEvents = False
Button1.Enabled = True
Button2.Enabled = False
EndSub
EndClass