FileSystemWatcher路径更新

FileSystemWatcher是常用的文件监视方法,其简单示例如下:

using System;
using System.IO;

namespace MyNamespace
{
    class MyClassCS
    {
        static void Main()
        {
            using var watcher = new FileSystemWatcher(@"C:\path\to\folder");

            watcher.NotifyFilter = NotifyFilters.Attributes
                                 | NotifyFilters.CreationTime
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.FileName
                                 | NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.Security
                                 | NotifyFilters.Size;

            watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            watcher.Deleted += OnDeleted;
            watcher.Renamed += OnRenamed;
            watcher.Error += OnError;

            watcher.Filter = "*.txt";
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType != WatcherChangeTypes.Changed)
            {
                return;
            }
            Console.WriteLine($"Changed: {e.FullPath}");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            string value = $"Created: {e.FullPath}";
            Console.WriteLine(value);
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e) =>
            Console.WriteLine($"Deleted: {e.FullPath}");

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine($"Renamed:");
            Console.WriteLine($"    Old: {e.OldFullPath}");
            Console.WriteLine($"    New: {e.FullPath}");
        }

        private static void OnError(object sender, ErrorEventArgs e) =>
            PrintException(e.GetException());

        private static void PrintException(Exception? ex)
        {
            if (ex != null)
            {
                Console.WriteLine($"Message: {ex.Message}");
                Console.WriteLine("Stacktrace:");
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine();
                PrintException(ex.InnerException);
            }
        }
    }
}

但是对于需要进行动态更新路径的需求,需要FileSystemWatcher更新监视路径,对此可以将监视路径的更改封装在一个方法中,并在触发条件满足时调用该方法。下面是一个简单的示例,演示如何在监视路径更新后重新设置FileSystemWatcher

using System;
using System.IO;

class Program
{
    static FileSystemWatcher watcher = new FileSystemWatcher();

    static void Main()
    {
        // 初始监视路径
        string initialPath = @"C:\path\to\directory";
        SetWatcher(initialPath);

        // 模拟条件触发,改变监视路径
        Console.WriteLine("Press 'c' to change the directory, 'q' to quit.");
        while (true)
        {
            var key = Console.ReadKey().KeyChar;
            if (key == 'q')
                break;
            else if (key == 'c')
            {
                Console.WriteLine("\nChanging directory...");
                string newPath = @"C:\new\path\to\directory"; // 新的监视路径
                SetWatcher(newPath);
            }
        }
    }

    static void SetWatcher(string path)
    {
        if (watcher.EnableRaisingEvents)
        {
            watcher.EnableRaisingEvents = false;
            watcher.Dispose();
            watcher = new FileSystemWatcher();
        }

        watcher.Path = path;
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.*"; // 监视所有文件
        watcher.IncludeSubdirectories = true; // 包括子目录

        // 添加事件处理程序
        watcher.Changed += OnChanged;
        watcher.Created += OnCreated;
        watcher.Deleted += OnDeleted;
        watcher.Renamed += OnRenamed;

        // 开始监视
        watcher.EnableRaisingEvents = true;

        Console.WriteLine($"Now watching: {path}");
    }

    // 文件或目录更改事件处理程序
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
    }

    // 文件或目录创建事件处理程序
    private static void OnCreated(object source, FileSystemEventArgs e)
    {
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
    }

    // 文件或目录删除事件处理程序
    private static void OnDeleted(object source, FileSystemEventArgs e)
    {
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
    }

    // 文件或目录重命名事件处理程序
    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
    }
}

在这个示例中,当用户按下'c'键时,会调用SetWatcher方法来更新监视路径。可以根据你的实际需求来替换触发条件和新路径。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FileSystemWatcher 是一个用于监视文件系统变化的类。它可以实时地监控指定目录中文件的创建、删除、更名和修改等操作,并触发相应的事件。因此,我们可以利用FileSystemWatcher 来实现文件的备份功能。 首先,我们需要创建一个 FileSystemWatcher 的实例,并设置它要监视的目录路径和需要监视的文件类型。例如,我们可以指定监视 "C:\Documents" 目录下的所有文本文件(txt): ```csharp FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = "C:\\Documents"; watcher.Filter = "*.txt"; ``` 然后,我们订阅 FileSystemWatcher 实例的 Created、Deleted、Renamed 和 Changed 等事件,对应文件的创建、删除、更名和修改操作。当有文件变化时,相应的事件处理程序将被触发。 ```csharp watcher.Created += new FileSystemEventHandler(OnFileCreated); watcher.Deleted += new FileSystemEventHandler(OnFileDeleted); watcher.Renamed += new RenamedEventHandler(OnFileRenamed); watcher.Changed += new FileSystemEventHandler(OnFileChanged); // 备份文件的方法 void BackupFile(string filePath) { // 实现文件备份的逻辑,可以是复制文件到指定的备份目录或使用压缩等方式备份 // ... } // 文件创建事件处理程序 void OnFileCreated(object sender, FileSystemEventArgs e) { BackupFile(e.FullPath); } // 文件删除事件处理程序 void OnFileDeleted(object sender, FileSystemEventArgs e) { // 如果需要,可以在文件删除时备份已删除的文件 BackupFile(e.FullPath); } // 文件更名事件处理程序 void OnFileRenamed(object sender, RenamedEventArgs e) { // 如果需要,可以在文件更名时备份已更名的文件 BackupFile(e.FullPath); } // 文件修改事件处理程序 void OnFileChanged(object sender, FileSystemEventArgs e) { // 如果需要,可以在文件修改时备份文件的旧版本 BackupFile(e.FullPath); } ``` 通过以上的代码,我们可以实现使用 FileSystemWatcher 监控指定目录下的文本文件,并在文件发生创建、删除、更名和修改操作时进行相应的备份操作。当然,根据实际需求,你可以根据不同的事件类型自定义备份操作,达到更灵活的备份功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值