c's method of data synchronization of USES the file monitor object filesystemwatcher

  • 2020-05-30 20:57:05
  • OfStack

Recently, there was a requirement in the project to get the contents of a text file that was changing irregularly in real time. First thought is to use the program on a regular basis to access this file, because of high requirement of real-time, interval of not more than 1 S, and every time to get to the text distributed to WEB servers are going to do other operations, and the text writes frequently, sometimes 1 second may repeatedly, but it is also possible in quite long period of time 1 is no writing.

One is an IO problem if you are accessing the file every second, and one is an IO problem if every operation will cause a reaction from the backend 1 series. If the text is not written for a long time, it is not desirable to trigger 1 series once every second.

Finally, we found the FileSystemWatcher object in c#. Before applying FileSystemWatcher, we first learned the basic properties and events of this object and popularized the basic knowledge of FileSystemWatcher.

FileSystemWatcher basis


Path - this property tells FileSystemWatcher which path it needs to monitor. For example, if we set this property to "C:\test", the object monitors all changes (including delete, modify, create, rename) to all files in the test directory.

IncludeSubDirectories - this property indicates whether the FileSystemWatcher object should monitor changes to the subdirectory (all files).

Filter - this property allows you to filter out changes to certain types of files. For example, if we only want to submit notifications when an TXT file is modified/created/deleted, we can set this property to "*txt". This property is handy when dealing with high traffic or large directories.

NotifyFilter -- gets or sets the type of change to monitor. You can step through the filter to monitor the type of change, such as watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite

| NotifyFilters.FileName | NotifyFilters.DirectoryName;


Changed -- commit this event when a file in the monitored directory is modified. It is worth noting that this event may be submitted multiple times, even if only one change occurs to the content of the file. This is because when you save the file, other properties of the file also change.

Created -- commit this event when a new file is created in the monitored directory. If you plan to use this event to move the new event, you must write some error handling code into the event handler that handles the current file being used by other processes. This is done because the Created event may be committed before the file is released by the process that created the file. If you don't have the code in place to handle this correctly, an exception may occur.

Deleted -- commit this event when a file in the monitored directory is deleted.

Renamed -- commit this event when a file in the monitored directory is renamed.

Note: if you do not set EnableRaisingEvents to true, the system will not commit any event. If there are times when the FileSystemWatcher object does not seem to work, check EnableRaisingEvents first to make sure it is set to true.

The event processing
When FileSystemWatcher calls an event handler, it contains two independent variables -- an object called "sender" and an FileSystemEventArgs object called "e". The independent variable we're interested in is FileSystemEventArgs. This object contains the reason for the event to be submitted. Here are some properties of the FileSystemEventArgs object:

Name -- the name of the file in this property that causes the event to be committed. It does not contain the path to the file -- only the file or directory name that was committed using the event.

ChangeType -- this is an WatcherChangeTypes that indicates which type of event to commit. Valid values include:





FullPath -- this property contains the full path to the file where the event was committed, including the file name and directory name.

Note: FileSystemEventArgs object is the independent variable when files are created, deleted and modified in the monitoring folder. If it is renamed, it will be RenamedEventArgs object. At this point, in addition to the property value of FileSystemEventArgs object, there is one more OldFullPath.

The above is the basic knowledge of FileSystemEventArgs. Most of them are found on the Internet and sorted out by themselves.

Here's how to use it:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
    /// <summary>
    /// MainWindow.xaml  Interaction logic 
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

        private void button1_Click(object sender, RoutedEventArgs e)
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"C:\test";
            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter = "*.txt";
            watcher.Changed += (s,e1)=> this.Dispatcher.Invoke(new Action(() =>
                label1.Content = e1.Name + " Be modified! ";
            watcher.Created += (s, e1) =>  this.Dispatcher.Invoke(new Action(() => { label1.Content = e1.Name + " Has been added! "; }));
            watcher.Deleted += (s, e1) =>  this.Dispatcher.Invoke(new Action(() => { label1.Content = e1.Name + " To be deleted! "; }));
            watcher.Renamed += (s, e1) =>  this.Dispatcher.Invoke(new Action(() =>
                label1.Content = e1.OldName + " Has been renamed to :"+e1.Name;
            // To monitor 
            watcher.EnableRaisingEvents = true;

Related articles: