C# 程序从文件中捕获事件
C# 为我们提供了某些功能,可以在文件或目录更改时引发事件。 FileSystemWatcher 类完成这项工作。此类是 System.IO 命名空间和 System.IO.FileSystem.Watcher.dll 程序集的一部分。它充当整个文件系统的看门狗。顾名思义,此类侦听对特定目录所做的更改。此外,它还提供了某些属性,可以使用这些属性来监听文件系统的变化。首先,可以创建此类的一个组件,该组件然后侦听本地计算机或远程计算机上的文件。当发生目录或文件更改时,它会做出响应。在本文中,我们将了解如何从文件中捕获事件。
句法:
public class FileSystemWatcher : System.ComponentModel.Component,
示例:在这个程序中,在指定位置发生的事件被捕获。在这里,位置是“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();
}
}
输出:
To exit press any key present on the keyboard