zoukankan      html  css  js  c++  java
  • C#(99):文件监视 FileSystemWatcher

    FileSystemWatcher

    FileSystemWatcher 类 (System.IO) | Microsoft Docs

    1、构造函数

    给定要监视的指定目录和文件类型,初始化 FileSystemWatcher 类的新实例。

    public FileSystemWatcher (string path, string filter);

    2、实例:

    下面的示例创建FileSystemWatcher监视在运行时指定的目录。 该组件设置为监视中的更改LastWriteLastAccess时间、 创建、 删除、 或重命名的目录中的文本文件。

    如果文件是更改、 创建,或删除,文件的路径将打印到控制台。 在一个文件重命名后,旧的和新路径将打印到控制台。

    static void Main()
    {
        Run();
    }
    
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private static void Run()
    {
        // 创建一个新的FileSystemWatcher并设置其属性.
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
    
            watcher.Path = "C:\aa\";
            
    // 只监视文本文件.
            watcher.Filter = "*.txt";
            // 监视LastAccess和LastWrite时间的变化,以及文件或目录的重命名.
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;// 添加事件处理程序.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;
    
            // 开始监视.
            watcher.EnableRaisingEvents = true;
    
            // 等待用户退出程序.
            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
    }
    
    // 定义事件处理程序。指定在更改、创建或删除文件时执行的操作.
    private static void OnChanged(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}");
  • 相关阅读:
    JS高程3:面向对象的程序设计——理解对象
    JS高程3:函数表达式
    JS高程3:事件
    JS高程3:表单脚本
    InnoDB:表
    InnoDB:文件
    Springboot项目配置druid数据库连接池,并监控统计功能
    linux上修改mysql登陆密码
    上传本地文件到GitHub上
    logback.xml的使用,将日志异步保存到数据库中
  • 原文地址:https://www.cnblogs.com/springsnow/p/14718863.html
Copyright © 2011-2022 走看看