zoukankan      html  css  js  c++  java
  • C#文件监控

    FileSystemWatcher

    常用属性:

    Path:获取或设置要监视的目录的路径

    Filter:获取或设置筛选字符串,用于确定在目录中监视哪些文件

    NotifyFilter:获取或设置要监视的更改类型。

    EnableRaisingEvents:获取或设置一个值,该值指示是否启用此组件。

    常用事件:

    OnChanged:执行Changed,Created,Deleted时引发改事件

    OnRenamed:执行重命名时引发改事件

    监控代码:(源码.rar)

      

    C#文件监控
     1 #region 监控文件
     2 public void Run()
     3 {
     4     //创建文件监控对象
     5     FileSystemWatcher watcher = new FileSystemWatcher();
     6     //设置监控目录
     7     watcher.Path = path;
     8     //定义监控类型
     9     watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
    10         | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime;
    11     //定义监控的文件类型
    12     watcher.Filter = "*.*";
    13 
    14     //绑定监控事件
    15     watcher.Changed += new FileSystemEventHandler(OnChanged);
    16     watcher.Created += new FileSystemEventHandler(OnChanged);
    17     watcher.Deleted += new FileSystemEventHandler(OnChanged);
    18     watcher.Renamed += new RenamedEventHandler(OnRenamed);
    19 
    20     //true表示开始监控,启用监控;false表示取消监控
    21     watcher.EnableRaisingEvents = true;
    22 }
    23 
    24 private void OnChanged(object source, FileSystemEventArgs e)
    25 {
    26             
    27     string changedInfo = string.Format("File: {0} {1}", e.FullPath, e.ChangeType);
    28     //因为UI上的线程非安全的,所以要使用Invoke
    29     this.Invoke(new Method(AddItem),changedInfo);
    30 }
    31 
    32 private void OnRenamed(object source, RenamedEventArgs e)
    33 {
    34         
    35     string changedInfo = string.Format("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    36     //因为UI上的线程非安全的,所以要使用Invoke
    37     this.Invoke(new Method(AddItem), changedInfo);
    38 
    39 }
    40 //把监控到的信息添加到ListBox上
    41 private void AddItem(string item)
    42 {
    43     listBox1.Items.Add(item);
    44 }
    45 #endregion
  • 相关阅读:
    JustOj 1936: 小明A+B
    Codeforce 835B
    Codeforce 835A
    Java读取Properties工具类
    IDEA2019 断点调试
    Pagination+AngularJS实现前端的分页
    PageHelper实现分页
    100多个免费API接口分享 调用完全不限次数,以后总用得着
    HDU 5763 Another Meaning KMP+DP
    Codeforces Round #365 (Div. 2) D. Mishka and Interesting sum 离线+线段树
  • 原文地址:https://www.cnblogs.com/guodf/p/2555478.html
Copyright © 2011-2022 走看看