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

2019-04-24  本文已影响0人  giveyoume

将开发过程中比较常用的一些内容收藏起来,下面内容内容是关于C#通过FileSystemWatcher监控文件添加或者删除事件的内容。

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.IncludeSubdirectories = true;

            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");

            }

            using (FileStream fs = new FileStream("test.bin", FileMode.Create)) {

            }

            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();

    }

}

上一篇 下一篇

猜你喜欢

热点阅读