在C#中,你可以使用System.IO.File
和System.Diagnostics.EventLog
類來記錄監控日志。以下是一個簡單的示例,展示了如何創建一個文件監視器來記錄日志:
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Watcher
{
class Program
{
static void Main(string[] args)
{
string folderPath = @"C:\path\to\folder";
string logFileName = "watcher.log";
string logFilePath = Path.Combine(folderPath, logFileName);
// 確保日志文件存在
if (!File.Exists(logFilePath))
{
File.Create(logFilePath);
}
// 創建一個監視器來監視文件夾中的文件更改
FileSystemWatcher watcher = new FileSystemWatcher(folderPath);
// 定義要監視的事件類型
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// 注冊事件處理程序
watcher.Changed += Watcher_Changed;
watcher.Created += Watcher_Created;
watcher.Deleted += Watcher_Deleted;
watcher.Renamed += Watcher_Renamed;
// 開始監視
watcher.EnableRaisingEvents = true;
Console.WriteLine("開始監視文件夾: " + folderPath);
Console.WriteLine("日志文件: " + logFilePath);
// 等待用戶按下任意鍵退出
Console.ReadKey();
// 停止監視并注銷事件處理程序
watcher.EnableRaisingEvents = false;
watcher.Changed -= Watcher_Changed;
watcher.Created -= Watcher_Created;
watcher.Deleted -= Watcher_Deleted;
watcher.Renamed -= Watcher_Renamed;
Console.WriteLine("監視已停止");
}
private static void Watcher_Changed(object source, FileSystemEventArgs e)
{
LogEvent("文件已更改: " + e.FullPath);
}
private static void Watcher_Created(object source, FileSystemEventArgs e)
{
LogEvent("文件已創建: " + e.FullPath);
}
private static void Watcher_Deleted(object source, FileSystemEventArgs e)
{
LogEvent("文件已刪除: " + e.FullPath);
}
private static void Watcher_Renamed(object source, RenamedEventArgs e)
{
LogEvent("文件已重命名: " + e.OldFullPath + " -> " + e.FullPath);
}
private static void LogEvent(string message)
{
// 獲取當前時間
DateTime now = DateTime.Now;
// 創建日志條目
StringBuilder logEntry = new StringBuilder();
logEntry.AppendLine($"{now}: {message}");
// 將日志條目追加到日志文件中
File.AppendAllText(logFilePath, logEntry.ToString());
// 可選: 將日志條目寫入事件日志
// EventLog.WriteEntry(logFilePath, message, EventLogEntryType.Information);
}
}
}
這個示例將監視指定的文件夾,并在文件更改時記錄日志。你可以根據需要修改folderPath
和logFileName
變量來指定要監視的文件夾和日志文件的路徑。