前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >C#-使用FileSystemWatcher类观察文件的更改

C#-使用FileSystemWatcher类观察文件的更改

作者头像
ccf19881030
发布2020-06-04 15:05:30
发布2020-06-04 15:05:30
2.1K00
代码可运行
举报
文章被收录于专栏:ccf19881030的博客ccf19881030的博客
运行总次数:0
代码可运行

FileSystemWatcher类

FileSystemWatcher类的主要功能: 监控指定文件或目录的文件的创建、删除、改动、重命名等活动。可以动态地定义需要监控的文件类型及文件属性改动的类型。 具体可以参考微软官方文档FileSystemWatcher Namespace: System.IO Assembly: System.dll Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.

观察文件的更改

使用FileSystemWatcher可以监视文件的更改。事件在创建、重命名、删除和更改文件时触发。这可用于如下场景:需要对文件的变更作出反应。例如,服务器上传文件时,或文件缓存在内存中,而缓存需要在文件更改时失效。 下面是一个FileMonitor的示例程序:

代码语言:javascript
代码运行次数:0
运行
复制
using System;
using System.IO;

namespace FileMonitor
{
    public class Program
    {
        private static FileSystemWatcher s_watcher;

        public static void Main(string[] args)
        {
            WatchFiles(".", "*.txt");
            Console.ReadLine();
            UnWatchFiles();
        }

        public static void WatchFiles(string path, string filter)
        {
            s_watcher = new FileSystemWatcher(path, filter)
            {
                IncludeSubdirectories = true
            };
            s_watcher.Created += OnFileChanged;
            s_watcher.Changed += OnFileChanged;
            s_watcher.Deleted += OnFileChanged;
            s_watcher.Renamed += OnFileRenamed;

            s_watcher.EnableRaisingEvents = true;
            Console.WriteLine("watching file changes...");
        }

        public static void UnWatchFiles()
        {
            s_watcher.Created -= OnFileChanged;
            s_watcher.Changed -= OnFileChanged;
            s_watcher.Deleted -= OnFileChanged;
            s_watcher.Renamed -= OnFileRenamed;
            s_watcher.Dispose();
            s_watcher = null;
        }

        private static void OnFileRenamed(object sender, RenamedEventArgs e) =>
            Console.WriteLine($"file {e.OldName} {e.ChangeType} to {e.Name}");

        private static void OnFileChanged(object sender, FileSystemEventArgs e) =>
            Console.WriteLine($"file {e.Name} {e.ChangeType}");
    }
}

微软官方示例程序

The following example creates a FileSystemWatcher to watch the directory specified at run time. The component is set to watch for changes in LastWrite and LastAccess time, the creation, deletion, or renaming of text files in the directory. If a file is changed, created, or deleted, the path to the file prints to the console. When a file is renamed, the old and new paths print to the console.

代码语言:javascript
代码运行次数:0
运行
复制
using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{
    public static void Main()
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private static void Run()
    {
        string[] args = Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if (args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = args[1];

            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            // Only watch text files.
            watcher.Filter = "*.txt";

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e) =>
        // Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");

    private static void OnRenamed(object source, RenamedEventArgs e) =>
        // Specify what is done when a file is renamed.
        Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
}

参考资料

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/06/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • FileSystemWatcher类
  • 观察文件的更改
  • 微软官方示例程序
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档