FileSystemWatcher類是C#中用于監視文件系統更改的類。它可以監視指定目錄中的文件和子目錄的創建、更改、重命名和刪除操作。
以下是使用FileSystemWatcher類的基本步驟:
FileSystemWatcher watcher = new FileSystemWatcher("目錄路徑");
watcher.Filter = "*.txt"; // 只監視文本文件
watcher.IncludeSubdirectories = true; // 包括子目錄中的文件
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
private static void OnCreated(object source, FileSystemEventArgs e)
{
// 處理文件創建事件
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
// 處理文件更改事件
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
// 處理文件刪除事件
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// 處理文件重命名事件
}
watcher.EnableRaisingEvents = true;
完整示例代碼:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher("目錄路徑");
watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = true;
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press 'q' to quit.");
while (Console.Read() != 'q') ;
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("Created: " + e.FullPath);
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("Changed: " + e.FullPath);
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("Deleted: " + e.FullPath);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("Renamed: " + e.OldFullPath + " to " + e.FullPath);
}
}
此示例會監視指定目錄中的所有文本文件的創建、更改、刪除和重命名事件,并在控制臺輸出相應的信息。按下"q"鍵退出程序。