溫馨提示×

如何在C#中使用Filewatcher

c#
小云
224
2023-09-27 04:22:40
欄目: 編程語言

要在C#中使用FileWatcher,首先需要創(chuàng)建一個FileWatcher對象,并設置所需的屬性和事件處理程序。

以下是一個簡單的示例,展示了如何在C#中使用FileWatcher來監(jiān)視文件的創(chuàng)建、修改和刪除事件:

using System;
using System.IO;
class Program
{
static void Main()
{
// 創(chuàng)建一個FileWatcher對象
FileSystemWatcher fileWatcher = new FileSystemWatcher();
// 設置要監(jiān)視的文件夾路徑
fileWatcher.Path = @"C:\YourFolderPath";
// 設置要監(jiān)視的文件類型
fileWatcher.Filter = "*.txt";
// 設置是否監(jiān)視子文件夾
fileWatcher.IncludeSubdirectories = false;
// 設置要監(jiān)視的事件
fileWatcher.Created += OnFileCreated;
fileWatcher.Changed += OnFileChanged;
fileWatcher.Deleted += OnFileDeleted;
// 啟動文件監(jiān)視
fileWatcher.EnableRaisingEvents = true;
// 等待退出程序
Console.WriteLine("Press 'q' to quit the program.");
while (Console.Read() != 'q') ;
}
// 文件創(chuàng)建事件處理程序
private static void OnFileCreated(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File created: {e.Name}");
}
// 文件修改事件處理程序
private static void OnFileChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File changed: {e.Name}");
}
// 文件刪除事件處理程序
private static void OnFileDeleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File deleted: {e.Name}");
}
}

在上面的示例中,創(chuàng)建了一個FileWatcher對象,并設置了要監(jiān)視的文件夾路徑、文件類型和要監(jiān)視的事件。然后,通過設置EnableRaisingEvents屬性為true來啟動文件監(jiān)視。

在事件處理程序中,可以編寫自定義的代碼來處理文件創(chuàng)建、修改和刪除事件。這里只是簡單地在控制臺輸出相應的消息。

注意:在使用FileWatcher之前,確保有足夠的權限來訪問要監(jiān)視的文件夾和文件。

0