C#如何利用FileSystemWatcher控件实现的文件监控的具体示例分享


当前第2页 返回上一页

实例 使用FileSystemWatche组件来监视运行时指定的目录:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

using System;

using System.IO;

public class watcher

{

  public static void Main(string[] args)

  {

    //如果没有指定目录,则退出程序

    if(args.Length!=1)

    {

      //显示调用程序的正确方法

      Console.WriteLine("usage:Watcher.exe(directory)");

      return;

    }

    //创建一个新的FileSystemWatcher并设置其属性

    FileSystemWatcher watcher=new FileSystemWatcher();

    watcher.Path=args[O];

    /*监视LastAcceSS和LastWrite时间的更改以及文件或目录的重命名*/

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

           NotifyFilters.FileName | NotifyFilters.DirectoryName;

    //只监视文本文件

    watcher.Filter="*.txt";

    //添加事件句柄

    //当由FileSystemWatcher所指定的路径中的文件或目录的

    //大小、系统属性、最后写时间、最后访问时间或安全权限

    //发生更改时,更改事件就会发生

    watcher.Changed +=new FileSystemEventHandler(OnChanged);

    //由FileSystemWatcher所指定的路径中文件或目录被创建时,创建事件就会发生

    watcher.Created +=new FileSystemEventHandler(OnChanged);

    //当由FileSystemWatcher所指定的路径中文件或目录被删除时,删除事件就会发生

    watcher.Deleted +=new FileSystemEventHandler(OnChanged) ;

    //当由FileSystemWatcher所指定的路径中文件或目录被重命名时,重命名事件就会发生

    watcher.Renamed +=new RenamedEventHandler(OnRenamed);

    //开始监视

    watcher.EnableRaisingEvents=true;

    //等待用户退出程序

    Console.WriteLine("Press\'q\' to quit the sample.");

    while(Console.Read()!='q');

  }

  //定义事件处理程序

  public static void OnChanged(object sender,FileSystemEventArgs e)

  {

    //指定当文件被更改、创建或删除时要做的事

    Console.WriteLine("file:"+e.FullPath+""+e.ChangeType);

  }

  public static void OnRenamed(object sender,RenamedEventArgs e)

  {

    //指定当文件被重命名时发生的动作

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

  }

}

以上就是C#如何利用FileSystemWatcher控件实现的文件监控的具体示例分享的详细内容!

返回前面的内容

相关阅读 >>

.net mvc 使用ueditor上传图片

c#中关于rabbitmq应用的图文代码详解

linux下搭建.net core环境方法步骤

.net framework类库的主要功能是什么?

.net是什么语言 视频

详细介绍.net技术大系概览?(图)

c#编写windows服务程序的图文详解

c#中datetime与时间戳转换的实例代码

c# winform跨线程访问控件的图文详解

使用c#操作windowad之添加对象到用户组

更多相关阅读请进入《FileSystemWatcher》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...