try
using System;
using System.ComponentModel;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace FileSystemWatcherTest1
{
public partial class Form1 : Form
{
private readonly FileSystemWatcher myWatcher = new FileSystemWatcher();
private BackgroundWorker myWorker1 = new BackgroundWorker();
private Regex r = new Regex(@".*\..*");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {}
private void Form1_Load(object sender, EventArgs e)
{
// Get this applications path.
string path = Application.ExecutablePath;
string[] results = path.Split(new[]{'\\'}, StringSplitOptions.None);
int num = results.Length - 1;
results.SetValue("", num);
string finalPath = String.Join("\\", results);
// set the Path property
myWatcher.Path = finalPath;
myWatcher.SynchronizingObject = this;
myWatcher.IncludeSubdirectories = true;
myWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.LastWrite |
NotifyFilters.Attributes | NotifyFilters.LastAccess | NotifyFilters.Size;
// add even handlers
myWatcher.Changed += myWatcher_Changed;
// Enable raising events
myWatcher.EnableRaisingEvents = true;
//textBox1.Text = "Path has been set on the FileSystemWatcher";
}
private void myWatcher_Changed(object sender, FileSystemEventArgs e)
{
MakeChanges(e.Name);
}
private void MakeChanges(string result)
{
textBox1.Text += result + Environment.NewLine;
}
}
}
The key is the line
myWatcher.SynchronizingObject = this;
as this forces the event to be raised on the UI thread.Due to the fact this class may be used in several different scenarios forcing this single threaded event behaviour would be a major performance hit when direct UI interaction isn't required - setting this property http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.synchronizingobject.aspx gives the full details.