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;//开启监控

    }

  • 相关阅读:
    面试题汇总
    桥接模式
    2010412 面试题
    2010412 面试题1
    访问者模式
    原码、反码、补码什么意思?有什么用?
    装饰模式
    mysql 忘记root密码 进行重置
    运维开源工具一览
    编写一个函数计算小费,小费为总账单的20%
  • 原文地址:https://www.cnblogs.com/sundh1981/p/13191010.html
Copyright © 2011-2022 走看看