C# Program to Trap Events From File
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#
using System;
using System.IO;
public class GFG{
static void nameModified( object theSender,
RenamedEventArgs eve)
{
Console.WriteLine( "{0} NameChanged to {1}" ,
eve.OldFullPath, eve.FullPath);
}
static void modified( object theSender,
FileSystemEventArgs eve)
{
Console.WriteLine(eve.FullPath + " " +
eve.ChangeType);
}
static public void Main()
{
FileSystemWatcher obj = new FileSystemWatcher();
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);
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
Share your thoughts in the comments
Please Login to comment...