I have a FileSystemWatcher in my code, and the event it's linked to isn't triggering when a file is changed. I watched it in Debug, and the path, notify filter and EnableRaisingEvents are all being set correctly. I've looked at several code examples for FileSystemWatcher and I'm not seeing what I did wrong.

Please help!

public partial class frm_main : Form
    {
        public frm_main()
        {
            InitializeComponent();
        }
        
        public FileSystemWatcher monitor;
        public ImageSet myImgSet;
            
        /// <summary>
        /// called when a folder is selected
        /// </summary>
        /// <param name="files">A string array of directories</param>
        private void DirSelected(string[] dir)
        {
            try
            {
                DirectoryInfo dirInfo = new DirectoryInfo(dir[0]);

                // start monitoring folder
                // DirSelected normally does a bunch of other stuff, currently commented out in my code
                FileWatcher(dirInfo);
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Sets up the file monitoring
        /// </summary>
        /// <param name="dir">The directory to be monitored</param>
        private void FileWatcher(DirectoryInfo dir)
        {
            // set up file watcher
            if (monitor == null)
            {
                monitor = new FileSystemWatcher();
            }

            monitor.Path = dir.FullName;
            monitor.NotifyFilter = NotifyFilters.LastWrite;

            //Only monitor .bmp files
            monitor.Filter = "*.bmp";
 
            monitor.Changed += new FileSystemEventHandler(MonitorChanged);

            // begin watching
            monitor.EnableRaisingEvents = true;
        }

        /// Event Handler for FileSystemWatcher
        private void MonitorChanged(object s, FileSystemEventArgs e)
        {
            MessageBox.Show(e.Name);
        }
    }

To be sure its not permissions

use this at the top of filewatcher
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]

also make sure dirinfo is a fully qualified path

and one last thing, why pass in the array to dirselected when you are only trying to poll the first folder

This article has been dead for over six months. Start a new discussion instead.