温馨提示×

c# watcher怎样记录监控日志

c#
小樊
82
2024-09-24 17:35:16
栏目: 编程语言

在C#中,你可以使用System.IO.FileSystem.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);
        }
    }
}

这个示例将监视指定的文件夹,并在文件更改时记录日志。你可以根据需要修改folderPathlogFileName变量来指定要监视的文件夹和日志文件的路径。

0