staddle
staddle

Reputation: 380

Problems accessing WindowsForms after creating FileSystemWatcher

For my project, I need to trigger a method, that changes the text in some textboxes after a file was created inside a given directory.

Therefore, I used a FileSystemWatcher and added an EventHandler to it as you can see here:

private void watch()
    {

        watcher = new FileSystemWatcher();
        watcher.Path = path;
        watcher.Filter = "*.osr";
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

After a file is created, the FileSystemWatcher successfully triggers the method, but an error is raised when I want to access the textboxes.

textBox.Text = path; //Error here

The error is: "System.InvalidOperationException" and it says, that I'm trying to access WindowsForms from another thread, but I never created another thread...

The fun thing is, that I also have a button to do the whole thing manually (so opening a file manually) and it works perfectly fine there.

Can you tell me why it is in another thread or how I could fix it?

Thanks

Upvotes: 0

Views: 39

Answers (2)

Felipe Correa
Felipe Correa

Reputation: 36

Currently, your FileSystemWatcher is on one thread and your UI on another one.

You need to call it using BeginInvoke, so it will be "managed" at the same thread of your UI.

Something like this:

public partial class Form1 : Form
{
    delegate void FileCreationUpdater(FileSystemEventArgs evt);
    FileSystemWatcher watcher = null;
    public Form1()
    {
        InitializeComponent();

        // instantiate a new FileSystemWatcher
        watcher = new FileSystemWatcher(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
        {
            // and starts it right away
            EnableRaisingEvents = true
        };

        // create a new updater delegate 
        FileCreationUpdater updater = new FileCreationUpdater(TextBoxUpdater);

        // when receiving Created events, Invoke updater.
        watcher.Created += (s, e) =>
        {
            /// passing parameter to the invoked method
            textBox1.BeginInvoke(updater, e);
        };
    }

    public void TextBoxUpdater(FileSystemEventArgs evt)
    {
        /// update path
        textBox1.Text = evt.FullPath;
    }
}

Upvotes: 2

Clifford Agius
Clifford Agius

Reputation: 181

The FileSystemWatcher will run on a separate thread so rather than trying to read the path from the other thread just do a lookup in the directory and see what has changed. Sorry in a rush so can't give a full answer.

Upvotes: 0

Related Questions