Open In App

C# Program to Trap Events From File

Improve
Improve
Like Article
Like
Save
Share
Report

C# provides us with certain functionalities that can raise events when a file or directory changes. FileSystemWatcher class does the job. This class is a part of the System.IO namespace and System.IO.FileSystem.Watcher.dll assembly. It acts as a watchdog for the entire file system. As the name suggests, this class listens for the changes that are made to a specific directory. Also, it provides certain properties using which one can listen to the file system changes. Firstly, one can create a component of this class which then listens to files on a local computer or a remote computer. It responds back when a directory or file change occurs. In this article, we will see how to trap events from the file.

Syntax:

public class FileSystemWatcher : System.ComponentModel.Component, 

Example: In this program, the events that happen in the specified locations are trapped. Here, the location is “c: \\GeeksforGeeks”.

C#




// C# program to trap events from the file
using System;
using System.IO;
  
public class GFG{
   
// Static function 
static void nameModified(object theSender, 
                         RenamedEventArgs eve) 
{
    Console.WriteLine("{0} NameChanged to {1}"
                      eve.OldFullPath, eve.FullPath);
}
  
// Static function
static void modified(object theSender, 
                     FileSystemEventArgs eve) 
{
    Console.WriteLine(eve.FullPath + " "
                      eve.ChangeType);
}
  
// Driver code
static public void Main()
{
      
      // Initiating FileSystemWatch class object
    FileSystemWatcher obj = new FileSystemWatcher();
    
      // Path or location
    obj.Path = "c:\\GeeksforGeeks";
    obj.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName |
                       NotifyFilters.LastAccess | NotifyFilters.LastWrite;
      
      obj.Filter = "";
    obj.Created += new FileSystemEventHandler(modified);
    obj.Deleted += new FileSystemEventHandler(modified);
    obj.Changed += new FileSystemEventHandler(modified);
    obj.Renamed += new RenamedEventHandler(nameModified);
      
      // Raising events on the instantiated object
      obj.EnableRaisingEvents = true;
    Console.WriteLine("To exit press any key present on the keyboard");
    Console.Read();
}
}


Output:

To exit press any key present on the keyboard


Last Updated : 26 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads