A detailed example of C's FileSystemWatcher usage

  • 2020-11-25 07:29:05
  • OfStack

This example details the FileSystemWatcher usage of C#. Share to everybody for everybody reference. Specific usage is as follows:

Main functions of FileSystemWatcher control:

Monitors the creation, deletion, modification, renaming, and other activities of files for a specified file or directory. You can dynamically define the types of files you want to monitor and the types of file attribute changes.

1. Several basic properties commonly used:

(1) Path: Set the path of the directory to be monitored.
(2) IncludeSubdirectories: Set whether to cascade monitor subdirectories in the specified path.
(3) Filter: Set the filter string to determine which types of files to monitor in the directory.
(4) NotifyFilter: Set which attribute changes in the file will trigger Changed events, and simultaneously monitor multiple attribute changes that can be combined by "or". (default is NotifyFilter. LastWrite | NotifyFilter. FileName | NotifyFilter. DirectoryName combination)
Item:
Attributes -- Properties for files or folders.
CreationTime -- When the file or folder was created.
DirectoryName -- Directory name. (common)
FileName -- File name. (common)
LastAccess -- The date on which a file or folder was opened once.
LastWrite -- The date of the last time you wrote to a file or folder.
Security -- Security Settings for files or folders.
Size -- The size of a file or folder. (common)
(5) EnableRaisingEvents: Set whether to start monitoring or not. (Default: false)

2. Common Events:

(1) Changed: When files and directories are changed, NotifyFilter property can be used to set the properties that trigger the event and require file changes.
(2) Created: Occurs when files and directories are created.
(3) Deleted: Occurs when a file or directory is deleted.
(4) Renamed: Occurs when a file or directory is renamed.
(5) FileSystemEventArgs Objects:
Member: Name: Gets the name of the affected file or directory. Note: In the case of cascading monitoring subdirectories, this value is the path from the next directory of the monitoring directory to the affected file, not just the affected file name.
FullPath: Gets the fully qualified path to the affected file or directory.
ChangeType: Gets the type of event that occurs for the affected file or directory.
Item:
All - Create, delete, change, or rename a file or folder.
Changed -- Changes to a file or folder. The types of changes include changes in size, properties, security Settings, last write time, and last access time.
Created -- Creation of a file or folder.
Deleted -- File or folder deletion.
Renamed -- Rename a file or folder.
(6) RenamedEventArgs Objects:
Member: Name: Gets the new name of the affected file or directory.
OldName: Gets the old name of the affected file or directory.
FullPath: Gets the fully qualified path to the affected file or directory.
OldFullPath: Gets the first fully qualified path to the affected file or directory.
ChangeType: Gets the type of event that occurs for the affected file or directory.
Item:
All -- Create, delete, change, or rename a file or folder.
Changed -- Changes to a file or folder. The types of changes include changes in size, properties, security Settings, last write time, and last access time.
Created - Creation of a file or folder.
Deleted - File or folder deletion.
Renamed -- Rename a file or folder.

Example:

private delegate void setLogTextDelegate(FileSystemEventArgs e); // Statement pass FileSystemEventArgs Object for a file Created . Deleted and Changed Time-varying update UI Interface. 
private delegate void renamedDelegate(RenamedEventArgs e);  // Statement pass RenamedEventArgs Object for a file Renamed When the update UI Interface.
FileSystemWatcher fsw= new FileSystemWatcher();
fsw.Path = " C:\ " ;   // Sets the directory of files to monitor
fsw.IncludeSubdirectories = true;   // Set up monitoring C All subdirectories under the disk directory
fsw.Filter = "*.txt|*.doc|*.jpg";   // Sets the type of the monitor file
fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size;   // Set file name, directory name, and file size changes to trigger Changed The event
fsw.Created += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle);  // A method for processing data after a binding event is triggered.
fsw.Deleted += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle);
fsw.Changed += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle);
fsw.Renamed += new RenamedEventHandler(this.fileSystemWatcher_Renamed);  // Rename events do not pass parameters with add, delete or change 1 The sample.
fsw.EnableRaisingEvents = true;  // Start the monitoring
private void fileSystemWatcher_EventHandle(object sender, FileSystemEventArgs e)  // A method that is called when a file is added or deleted
{
     if (this.listView1.InvokeRequired)  // Determines whether it crosses threads
      {
           this.listView1.Invoke(new setLogTextDelegate(setLogText), new object[] { e });   // Marshalling a method to using a delegate UI Main thread processing
      }
}
private void fileSystemWatcher_Renamed(object sender,RenamedEventArgs e)   // The processing method that is called when a file is renamed
{
      if (this.listView1.InvokeRequired) // Determines whether it crosses threads
       {
           this.listView1.Invoke(new renamedDelegate(setRenamedLogText), new object[] { e });  // Marshalling a method to using a delegate UI Main thread processing
       }
}
private void setLogText(FileSystemEventArgs e)  // update UI interface
{
      ListViewItem lvi = new ListViewItem();
      lvi.SubItems.Add(e.Name);   // Affected file name
      lvi.SubItems.Add(e.ChangeType.ToString());   // The change type of the affected file ( May be Created , Changed , Deleted )
      lvi.SubItems.Add(e.FullPath);     // The full path of the affected file
      this.listView1.Items.Add(lvi);
}
 private void setRenamedLogText(RenamedEventArgs e)  // update UI interface
{
       ListViewItem lvi = new ListViewItem();
       lvi.SubItems.Add(e.OldName);   // The original name of the affected document
       lvi.SubItems.Add(e.ChangeType.ToString());  // Types of changes to affected files ( Rename )
       lvi.SubItems.Add(e.Name);   // The new name of the affected file
       lvi.SubItems.Add(e.OldFullPath);     // The original path of the affected file
       lvi.SubItems.Add(e.FullPath);  // The full path of the affected file (real and original paths) 1 Sample)
       this.fileEventLog_lvw.Items.Add(lvi);
 }

Key points:

1. Since the FileSystemWatcher class is itself a multithreaded control, it automatically creates a thread for every instance of FileSystemWatcher.
2. We need to update the UI interface across threads using the delegate. Since the rename event passes the RenameEventArgs object and the create, modify, and delete event passes the FileEventArgs object, we need to declare two delegates.
3. If you need to monitor multiple files at the same time (such as the whole monitoring system), you only need to create an FileSystemWatcher array, with one FileSystemWatcher for each file

Hopefully this article has helped you with your C# programming.


Related articles: