zoukankan      html  css  js  c++  java
  • 文件监控系统

    文件监控FileSystemWatcher类,主要用于监控系统上制定的文件异动。该类位于System.Io,

    NotifyFilters枚举类型的属性是决定其监控文件那些行为的关键,(在WPF中有一个INotifyPropertyChanged的接口监控对象属性变化的通知)

    public enum NotifyFilters{

    Attributes,CreateTime,DirectoryName,FileName,LastAccess,LastWrite,Security

    }

    使用FileSystemWatcher类的第一步是为其设置Path属性,即监控的目标目录,还需要定义扩展名属性,例如:

    //1.确定要观察的目录的路径

    FileSystemWatcher watcher=new FileSystemWatcher();

    try{

      watcher.Path=@"DTest";

    }catch(Exception ex)

    {

      Console.WriteLine(ex.message);

    }

    //确定要“留意”的事情

    watcher.NotifyFilter=NotifyFilters.LastAccess|NotifyFilters.LastWrite|NotifyFilters.FileName|NotifyFilters.DirectoryName

    //确定要观察的类型

    watcher.Filter="*.*";

    watcher.Changed+=new FileSystemEventHandler(OnChanged);

    watcher.Created+=new FileSystemEventHandler(OnChanged);

    watcher.Delete+=new FileSystemEventHandler(OnChanged);

    watcher.Renamed+=new RenamedEventHandler(OnRenamed);

    //开始观察目录

    watcher.EnableRaisingEvents=true;

    while(Console.Read()!='q');  //输入q退出

    }

    static void OnChanged(object source,FileSystemEventArgs e)

    {

      //指定当文本改变、创建、删除的时候需要做的事情

      Console.WriteLine("File:{0} {1}",e.FullPath,e.ChangedType);

    }

    static void OnRenamed(object source,RenamedEventArgs e)

    {

    //指定当文件重命名的时候需要做的事情

    Console.WriteLine("File:{0} renamed {1}",e.OldFullPath,e.FullPath);

    以上步骤可归纳为:1.FileSystemWatcher watcher=new FileSystemWatcher() //实例化对象 

                                    2.watcher.Path=@"D: est"; //指定目录

                                    3.watcher.NotifyFilter=NotifyFilters.LastAcces|NotifyFilters.LastWrite|NotifyFilters.FileName|NotifyFilters.DirectoryName;//设定关注事件

                                   4.watcher.Filter="*.*"; //设置监控文件类型

                                   5.watcher.changed=watcher.Deleted=watcher.Created+=new FileSystemEventHandler(OnChanged); //绑定委托方法,指定收到通知时触发事件

                                   6.watcher.EnableRaiseEvents=true;//开启监控

    }

  • 相关阅读:
    计算机网络第一章_20210512
    bootloader_华清远见
    C#3.17
    linux--cd命令
    国内的开源网站
    安装linux
    如何自我介绍
    课堂破冰游戏“猜猜他是谁”
    办公软件---word
    计算机网络--技能训练
  • 原文地址:https://www.cnblogs.com/sundh1981/p/13191010.html
Copyright © 2011-2022 走看看