返回

掌握文件变动情况,C# FileSystemWatcher 带来实时监控方案

后端

监控文件变动:使用 C# 中的 FileSystemWatcher

文件监控的意义

在现代数字世界中,文件是至关重要的资产,它们包含着我们宝贵的信息和数据。然而,这些文件很容易受到意外删除、恶意软件感染或其他事故的影响。因此,密切监控文件变动情况变得至关重要,这样我们才能在第一时间采取适当的行动,保护我们的数据。

FileSystemWatcher:监控文件的利器

C# 中的 FileSystemWatcher 类为我们提供了监控文件变动的强大工具。它能够实时监视指定文件夹及其子文件夹中的文件,并及时通知我们任何创建、修改或删除操作。

使用 FileSystemWatcher 监控文件变动的步骤

实现文件监控需要几个简单的步骤:

  1. 创建 FileSystemWatcher 对象: 指定要监视的文件夹路径,以及要关注的事件类型(如创建、修改、删除)。
  2. 启用文件监控: 调用 EnableRaisingEvents() 方法启动文件监控。
  3. 添加事件处理程序: 针对不同的文件变动事件添加相应的处理程序,如记录日志或采取其他适当的行动。

代码示例

以下代码示例展示了如何使用 FileSystemWatcher 监控文件变动:

using System;
using System.IO;

namespace FileMonitor
{
    class Program
    {
        static void Main(string[] args)
        {
            // 指定要监控的文件夹路径
            string folderPath = @"C:\Users\Public\Downloads";

            // 创建 FileSystemWatcher 对象
            FileSystemWatcher watcher = new FileSystemWatcher();

            // 设置要监视的文件变动类型
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName |
                                NotifyFilters.LastWrite | NotifyFilters.CreationTime;

            // 设置要监视的文件夹路径
            watcher.Path = folderPath;

            // 添加事件处理程序
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.Deleted += new FileSystemEventHandler(OnDeleted);

            // 启动文件监控
            watcher.EnableRaisingEvents = true;

            // 保持控制台窗口运行,以便持续监控文件变动
            Console.WriteLine("按 'q' 退出.");
            while (Console.ReadKey().KeyChar != 'q')
            {
                // 无操作
            }
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(
using System;
using System.IO;

namespace FileMonitor
{
    class Program
    {
        static void Main(string[] args)
        {
            // 指定要监控的文件夹路径
            string folderPath = @"C:\Users\Public\Downloads";

            // 创建 FileSystemWatcher 对象
            FileSystemWatcher watcher = new FileSystemWatcher();

            // 设置要监视的文件变动类型
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName |
                                NotifyFilters.LastWrite | NotifyFilters.CreationTime;

            // 设置要监视的文件夹路径
            watcher.Path = folderPath;

            // 添加事件处理程序
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.Deleted += new FileSystemEventHandler(OnDeleted);

            // 启动文件监控
            watcher.EnableRaisingEvents = true;

            // 保持控制台窗口运行,以便持续监控文件变动
            Console.WriteLine("按 'q' 退出.");
            while (Console.ReadKey().KeyChar != 'q')
            {
                // 无操作
            }
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已修改");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已创建");
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已删除");
        }
    }
}
quot;文件 {e.FullPath} 已修改"
); } private static void OnCreated(object sender, FileSystemEventArgs e) { Console.WriteLine(
using System;
using System.IO;

namespace FileMonitor
{
    class Program
    {
        static void Main(string[] args)
        {
            // 指定要监控的文件夹路径
            string folderPath = @"C:\Users\Public\Downloads";

            // 创建 FileSystemWatcher 对象
            FileSystemWatcher watcher = new FileSystemWatcher();

            // 设置要监视的文件变动类型
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName |
                                NotifyFilters.LastWrite | NotifyFilters.CreationTime;

            // 设置要监视的文件夹路径
            watcher.Path = folderPath;

            // 添加事件处理程序
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.Deleted += new FileSystemEventHandler(OnDeleted);

            // 启动文件监控
            watcher.EnableRaisingEvents = true;

            // 保持控制台窗口运行,以便持续监控文件变动
            Console.WriteLine("按 'q' 退出.");
            while (Console.ReadKey().KeyChar != 'q')
            {
                // 无操作
            }
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已修改");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已创建");
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已删除");
        }
    }
}
quot;文件 {e.FullPath} 已创建"
); } private static void OnDeleted(object sender, FileSystemEventArgs e) { Console.WriteLine(
using System;
using System.IO;

namespace FileMonitor
{
    class Program
    {
        static void Main(string[] args)
        {
            // 指定要监控的文件夹路径
            string folderPath = @"C:\Users\Public\Downloads";

            // 创建 FileSystemWatcher 对象
            FileSystemWatcher watcher = new FileSystemWatcher();

            // 设置要监视的文件变动类型
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName |
                                NotifyFilters.LastWrite | NotifyFilters.CreationTime;

            // 设置要监视的文件夹路径
            watcher.Path = folderPath;

            // 添加事件处理程序
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.Deleted += new FileSystemEventHandler(OnDeleted);

            // 启动文件监控
            watcher.EnableRaisingEvents = true;

            // 保持控制台窗口运行,以便持续监控文件变动
            Console.WriteLine("按 'q' 退出.");
            while (Console.ReadKey().KeyChar != 'q')
            {
                // 无操作
            }
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已修改");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已创建");
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件 {e.FullPath} 已删除");
        }
    }
}
quot;文件 {e.FullPath} 已删除"
); } } }

应用场景

FileSystemWatcher 在以下场景中有着广泛的应用:

  • 实时备份重要文件: 创建一个后台进程,持续监控重要文件的变动,一旦发现文件修改,立即备份到安全位置。
  • 同步本地和云端文件: 当本地文件变动时,及时同步到云端,确保数据始终保持一致。
  • 自动执行文件处理任务: 当特定文件变动时,自动触发某些任务,如发送邮件、启动应用程序等。
  • 检测病毒或恶意软件感染: 监控特定文件或文件夹的变化,一旦发现可疑活动,及时采取行动。

常见问题解答

  • FileSystemWatcher 能监控网络驱动器上的文件吗?
    不,FileSystemWatcher 只能监控本地文件系统上的文件。

  • FileSystemWatcher 如何处理大文件夹?
    FileSystemWatcher 会监控文件夹及其所有子文件夹,因此监控大文件夹可能会导致性能问题。

  • FileSystemWatcher 可以在多个文件夹上运行吗?
    是的,FileSystemWatcher 可以同时监控多个文件夹,只需为每个文件夹创建单独的实例即可。

  • FileSystemWatcher 如何处理已删除的文件?
    FileSystemWatcher 无法检测到已删除的文件,它只能检测到创建、修改和重命名操作。

  • FileSystemWatcher 如何处理同时发生多个文件变动的情况?
    FileSystemWatcher 会为每个文件变动触发单独的事件,即使这些变动同时发生。