Search code examples
c#treeviewfilesystemwatcher

Update UI control by FileSystemWatcher


Im having some problems in my code:

private void start_watcher()
    {
        fswFiler = new FileSystemWatcher(Control.filer.get_path(),"*.*");

        //fswStorage = new FileSystemWatcher(Control.storage.get_path());

        fswFiler.Changed += new FileSystemEventHandler(updatePend);
        fswFiler.Deleted += new FileSystemEventHandler(updatePend);
        fswFiler.Created += new FileSystemEventHandler(updatePend);
        fswFiler.Renamed += new RenamedEventHandler(updatePend);

        fswFiler.EnableRaisingEvents = true;

    }

    private void updatePend(object sender, FileSystemEventArgs e)
    {
        this.viewPend.Nodes.Clear();
        Control.filer.refresh_files_list();
        this.viewPend.Nodes.Add(Control.filer.get_files_node());
    }

throws me out of the program. any idea why is that happening ?


Solution

  • The FileSystemWatcher notifications occur in another thread than the UI uses. You must Invoke See: how to update a windows form GUI from another class?

    Or even better: How to update the GUI from another thread in C#?