FileSystemWatcher with c# appears to not be working.

The code below is being used to monitor c:\test but doesn't.  I can create a file in the test directory and change it but never get notified.

Any idea why not?

private void Form1_Load(object sender, EventArgs e)
        {
            FileSystemWatcher watcher = new FileSystemWatcher("C:\\test\\", "*.txt")
            {
                IncludeSubdirectories = true
            };

            toolStripStatusDirectory.Text = "Monitoring C:\\test";
            statusStrip1.Refresh();

            watcher.NotifyFilter &= NotifyFilters.LastAccess | NotifyFilters.LastWrite
                      | NotifyFilters.FileName | NotifyFilters.DirectoryName| NotifyFilters.CreationTime;

            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);

            watcher.EnableRaisingEvents = true;
        }
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            toolStripStatusCurrent.Text = "File //: " + e.FullPath + " " + e.ChangeType;
        }

Open in new window

Sheldon LivingstonConsultantAsked:
Who is Participating?
 
Ares KurkluConnect With a Mentor Software EngineerCommented:
So the program is running with no error? but the event is not firing? can you just put break points and trace it? see if it is even hitting the OnChanged event?
0
 
Sheldon LivingstonConsultantAuthor Commented:
Perfect!!!!  So the break point demonstrated that the code was working.

I was looking for some text to appear in the StripStatus... but the StripStatus was so small that I had to expand the form to see the text.

It was working all along and your tip helped me see that.

Thanks!
0
 
it_saigeDeveloperCommented:
The problem is that you define the FileSystemWatcher in the Form Load event but don't assign it to a property/field.  Therefore, when your code leaves the event, the FileSystemWatcher is disposed and garbage collected.  Try this -

Form1.cs -
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;

namespace EE_Q29065299
{
    public partial class Form1 : Form
    {
        readonly FileSystemWatcher watcher = default(FileSystemWatcher);
        public Form1()
        {
            InitializeComponent();
            watcher = new FileSystemWatcher(@"C:\_admin", "*.txt")
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
                NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite
            };
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
        }

        void OnChanged(object sender, FileSystemEventArgs e)
        {
            textBox1.HandleInvokeRequired(tb => tb.AppendText($"File //: {e.FullPath}; {e.ChangeType}{Environment.NewLine}"));
        }
    }

    static class Extensions
    {
        public static void HandleInvokeRequired<T>(this T control, Action<T> action) where T : Control, ISynchronizeInvoke
        {
            //Check to see is the control is not null
            if (control == null)
                throw new ArgumentNullException(string.Format("Cannot execute {0} on {1}.  {1} is null.", action, control));

            //Check to see if the control is disposed.
            if (control is Control && (control as Control).IsDisposed)
                throw new ObjectDisposedException(string.Format("Cannot execute {0} on {1}.  {1} is disposed.", action, control));

            //Check to see if the handle is created for the control.
            if (control is Control && !(control as Control).IsHandleCreated)
                throw new InvalidOperationException(string.Format("Cannot execute {0} on {1}.  Handle is not created for {1}.", action, control));

            //Check to see if the control's InvokeRequired property is true
            if (control.InvokeRequired)
            {
                try
                {
                    //Use Invoke() to invoke your action
                    control.Invoke(action, new object[] { control });
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Cannot execute {0} on {1}.  {2}.", action, control, ex.Message));
                }
            }
            else
            {
                try
                {
                    //Perform the action
                    action(control);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Cannot execute {0} on {1}.  {2}.", action, control, ex.Message));
                }
            }
        }
    }
}

Open in new window

Form1.Designer.cs -
namespace EE_Q29065299
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(13, 13);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ReadOnly = true;
            this.textBox1.Size = new System.Drawing.Size(459, 236);
            this.textBox1.TabIndex = 0;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(484, 261);
            this.Controls.Add(this.textBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
    }
}

Open in new window

Produces the following output -Capture.PNG
-saige-
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.