前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#通过FileSystemWatcher监控文件添加或者删除事件

C#通过FileSystemWatcher监控文件添加或者删除事件

原创
作者头像
用户7108768
修改2021-11-02 14:42:37
5930
修改2021-11-02 14:42:37
举报

C#通过FileSystemWatcher监控文件添加或者删除事件,当监控的目录里的文件增加或者删除时会触发指定的事件

代码语言:javascript
复制
using System;
using System.IO;
using System.Windows.Forms;
class MainClass {
    static void Main(string[] args) {
        using (FileSystemWatcher watch = new FileSystemWatcher()) {
            watch.Path = Application.StartupPath;
            watch.Filter = ".";
            watch.IncludeSubdirectories = true;

        // Attach the event handler.
        watch.Created += new FileSystemEventHandler(OnCreatedOrDeleted);
        watch.Deleted += new FileSystemEventHandler(OnCreatedOrDeleted);
        watch.EnableRaisingEvents = true;

        Console.WriteLine("Press Enter to create a  file.");
        Console.ReadLine();

        if (File.Exists("test.bin")) {
            File.Delete("test.bin");
        }

        // Create test.bin.
        using (FileStream fs = new FileStream("test.bin", FileMode.Create)) {
            // Do something.
        }

        Console.WriteLine("Press Enter to terminate the application.");
        Console.ReadLine();
    }
}

private static void OnCreatedOrDeleted(object sender, FileSystemEventArgs e) {
    Console.WriteLine("\tNOTIFICATION: " + e.FullPath + "' was " + e.ChangeType.ToString());
    Console.WriteLine();
}

}</pre> 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档