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

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

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

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:C#判断远程计算机的指定端口是否打开

下一篇:使用JSONP解决跨域问题-代码示例