谈谈C#文件监控对象FileSystemWatcher使用感受

2023-10-31 23:32

本文主要是介绍谈谈C#文件监控对象FileSystemWatcher使用感受,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在项目中有这么个需求,就是得去实时获取某个在无规律改变的文本文件中的内容。首先想到的是用程序定期去访问这个文件,因为对实时性要求很高,间隔不能超过1S,而且每次获取到文本内容都要去分发给WEB服务器做别的操作,而那个文本的写入有时候会频繁,1秒可能多次,但是也有可能在相当长一段时间内是没有任何写入的。

这样一来如果每秒都去访问文件的话,一个是IO问题,还有就是每次操作都会引起后端一系列程序的反应,文本在长时间内无写入的话,一秒一次的触发一系列徒劳的事情太不可取了。

最终发现了c#中的FileSystemWatcher对象,在应用FileSystemWatcher之前,首先了解一下这个对象的基本属性和事件,首先普及一下FileSystemWatcher基本知识。

FileSystemWatcher基础

属性:

    Path——这个属性告诉FileSystemWatcher它需要监控哪条路径。例如,如果我们将这个属性设为“C:\test”,对象就监控test目录下所有文件发生的所有改变(包括删除,修改,创建,重命名)。

    IncludeSubDirectories——这个属性说明FileSystemWatcher对象是否应该监控子目录中(所有文件)发生的改变。

    Filter——这个属性允许你过滤掉某些类型的文件发生的变化。例如,如果我们只希望在TXT文件被修改/新建/删除时提交通知,可以将这个属性设为“*txt”。在处理高流量或大型目录时,使用这个属性非常方便。

NotifyFilter——获取或设置要监视的更改类型。可以进一步的过滤要监控的更改类型,如watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite

           | NotifyFilters.FileName | NotifyFilters.DirectoryName;

事件:

    Changed——当被监控的目录中有一个文件被修改时,就提交这个事件。值得注意的是,这个事件可能会被提交多次,即使文件的内容仅仅发生一项改变。这是由于在保存文件时,文件的其它属性也发生了改变。

    Created——当被监控的目录新建一个文件时,就提交这个事件。如果你计划用这个事件移动新建的事件,你必须在事件处理器中写入一些错误处理代码,它能处理当前文件被其它进程使用的情况。之所以要这样做,是因为Created事件可能在建立文件的进程释放文件之前就被提交。如果你没有准备正确处理这种情况的代码,就可能出现异常。

    Deleted——当被监控的目录中有一个文件被删除,就提交这个事件。

    Renamed——当被监控的目录中有一个文件被重命名,就提交这个事件。 

 

注:如果你没有将EnableRaisingEvents设为真,系统不会提交任何一个事件。如果有时FileSystemWatcher对象似乎无法工作,请首先检查EnableRaisingEvents,确保它被设为真。

 

事件处理

 

FileSystemWatcher调用一个事件处理器时,它包含两个自变量——一个叫做“sender”的对象和一个叫做“e”的 FileSystemEventArgs对象。我们感兴趣的自变量为FileSystemEventArgs自变量。这个对象中包含有提交事件的原因。以下是FileSystemEventArgs对象的一些属性:

 

属性:

 

  Name——这个属性中使事件被提交的文件的名称。其中并不包含文件的路径——只包含使用事件被提交的文件或目录名称。

  ChangeType——这是一个WatcherChangeTypes,它指出要提交哪个类型的事件。其有效值包括:

  Changed

  Created

  Deleted

  Renamed

  FullPath——这个属性中包含使事件被提交的文件的完整路径,包括文件名和目录名。

 

注意:FileSystemEventArgs对象是监控文件夹下有文件创建、删除、修改时的自变量,如果是重命名的话为RenamedEventArgs对象此时除了FileSystemEventArgs对象的属性值,多了一个OldFullPath,为重命名之前的文件名。

 

以上为FileSystemEventArgs的基本知识,大部分是从网上搜找的然后自己稍微整理了一下。

 

下面为简单用法:

 

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.IO;
namespace test
{
     class Program
     {
         static void Main( string [] args)
         {
             WatcherStrat( @"C:\test" , "*.txt" );
             //由于是控制台程序,加个输入避免主线程执行完毕,看不到监控效果
             Console.ReadKey();
         }
       
         private static void WatcherStrat( string path, string filter)
         {
             FileSystemWatcher watcher = new FileSystemWatcher();
             watcher.Path = path;
             watcher.Filter = filter;
             watcher.Changed += new FileSystemEventHandler(OnProcess);
             watcher.Created += new FileSystemEventHandler(OnProcess);
             watcher.Deleted += new FileSystemEventHandler(OnProcess);
             watcher.Renamed += new RenamedEventHandler(OnRenamed);
             watcher.EnableRaisingEvents = true ;
         }
         private static void OnProcess( object source, FileSystemEventArgs e)
         {
             if (e.ChangeType == WatcherChangeTypes.Created)
             {
                 OnCreated(source, e);
             }
             else if (e.ChangeType == WatcherChangeTypes.Changed)
             {
                 OnChanged(source, e);
             }
             else if (e.ChangeType == WatcherChangeTypes.Deleted)
             {
                 OnDeleted(source, e);
             }
         }
         private static void OnCreated( object source, FileSystemEventArgs e)
         {
             Console.WriteLine( "文件新建事件处理逻辑" );
             
         }
         private static void OnChanged( object source, FileSystemEventArgs e)
         {
             Console.WriteLine( "文件改变事件处理逻辑" );
         }
         private static void OnDeleted( object source, FileSystemEventArgs e)
         {
             Console.WriteLine( "文件删除事件处理逻辑" );
         }
         private static void OnRenamed( object source, RenamedEventArgs e)
         {
             Console.WriteLine( "文件重命名事件处理逻辑" );
         }
     }
}

 

 

 

 

 

 

用上面的方法会发现,在一次文本文件变化的时候OnChanged事件会触发两次,这是因为除了文本内容变化之外还有文件其他的属性也变化了例如修改时间。

     

     为了解决这问题,也便于项目当中实际使用,写了下面几个类来实际使用:

 主方法:
 
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;
namespace test
{
     class Program
     {
         static void Main( string [] args)
         {
             MyFileSystemWather myWather = new MyFileSystemWather( @"C:\test" , "*.txt" );
             myWather.OnChanged += new FileSystemEventHandler(OnChanged);
             myWather.OnCreated += new FileSystemEventHandler(OnCreated);
             myWather.OnRenamed += new RenamedEventHandler(OnRenamed);
             myWather.OnDeleted += new FileSystemEventHandler(OnDeleted);
             myWather.Start();
             //由于是控制台程序,加个输入避免主线程执行完毕,看不到监控效果
             Console.ReadKey();
         }
         private static void OnCreated( object source, FileSystemEventArgs e)
         {
             Console.WriteLine( "文件新建事件处理逻辑" );
             
         }
         private static void OnChanged( object source, FileSystemEventArgs e)
         {
             Console.WriteLine( "文件改变事件处理逻辑" );
         }
         private static void OnDeleted( object source, FileSystemEventArgs e)
         {
             Console.WriteLine( "文件删除事件处理逻辑" );
         }
         private static void OnRenamed( object source, RenamedEventArgs e)
         {
             Console.WriteLine( "文件重命名事件处理逻辑" );
         }
     }
}

 

 

  WatcherProcess类:

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
51
52
53
54
using System.IO;
namespace test
{
     public class WatcherProcess
     {
         private object sender;
         private object eParam;
         public event RenamedEventHandler OnRenamed;
         public event FileSystemEventHandler OnChanged;
         public event FileSystemEventHandler OnCreated;
         public event FileSystemEventHandler OnDeleted;
         public event Completed OnCompleted;
         public WatcherProcess( object sender, object eParam)
         {
             this .sender = sender;
             this .eParam = eParam;
         }
         public void Process()
         {
             if (eParam.GetType() == typeof (RenamedEventArgs))
             {
                 OnRenamed(sender, (RenamedEventArgs)eParam);
                 OnCompleted(((RenamedEventArgs)eParam).FullPath);
             }
             else
             {
                 FileSystemEventArgs e = (FileSystemEventArgs)eParam;
                 if (e.ChangeType == WatcherChangeTypes.Created)
                 {
                     OnCreated(sender, e);
                     OnCompleted(e.FullPath);
                 }
                 else if (e.ChangeType == WatcherChangeTypes.Changed)
                 {
                     OnChanged(sender, e);
                     OnCompleted(e.FullPath);
                 }
                 else if (e.ChangeType == WatcherChangeTypes.Deleted)
                 {
                     OnDeleted(sender, e);
                     OnCompleted(e.FullPath);
                 }
                 else
                 {
                     OnCompleted(e.FullPath);
                 }
             }
         }
     }
}

 

  

MyFileSystemWather类:

   

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using System;
using System.Collections;
using System.IO;
using System.Threading;
namespace test
{
     public delegate void Completed( string key);
     public class MyFileSystemWather
     {
         private FileSystemWatcher fsWather;
         private Hashtable hstbWather;
         public event RenamedEventHandler OnRenamed;
         public event FileSystemEventHandler OnChanged;
         public event FileSystemEventHandler OnCreated;
         public event FileSystemEventHandler OnDeleted;
         /// <summary>
         /// 构造函数
         /// </summary>
         /// <param name="path">要监控的路径</param>
         public MyFileSystemWather( string path, string filter)
         {
             if (!Directory.Exists(path))
             {
                 throw new Exception( "找不到路径:" + path);
             }
             hstbWather = new Hashtable();
             fsWather = new FileSystemWatcher(path);
             // 是否监控子目录
             fsWather.IncludeSubdirectories = false ;
             fsWather.Filter = filter;
             fsWather.Renamed += new RenamedEventHandler(fsWather_Renamed);
             fsWather.Changed += new FileSystemEventHandler(fsWather_Changed);
             fsWather.Created += new FileSystemEventHandler(fsWather_Created);
             fsWather.Deleted += new FileSystemEventHandler(fsWather_Deleted);
         }
         /// <summary>
         /// 开始监控
         /// </summary>
         public void Start()
         {
             fsWather.EnableRaisingEvents = true ;
         }
         /// <summary>
         /// 停止监控
         /// </summary>
         public void Stop()
         {
             fsWather.EnableRaisingEvents = false ;
         }
         /// <summary>
         /// filesystemWatcher 本身的事件通知处理过程
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
         private void fsWather_Renamed( object sender, RenamedEventArgs e)
         {
             lock (hstbWather)
             {
                 hstbWather.Add(e.FullPath, e);
             }
             WatcherProcess watcherProcess = new WatcherProcess(sender, e);
             watcherProcess.OnCompleted += new Completed(WatcherProcess_OnCompleted);
             watcherProcess.OnRenamed += new RenamedEventHandler(WatcherProcess_OnRenamed);
             Thread thread = new Thread(watcherProcess.Process);
             thread.Start();
         }
         private void WatcherProcess_OnRenamed( object sender, RenamedEventArgs e)
         {
             OnRenamed(sender, e);
         }
         private void fsWather_Created( object sender, FileSystemEventArgs e)
         {
             lock (hstbWather)
             {
                 hstbWather.Add(e.FullPath, e);
             }
             WatcherProcess watcherProcess = new WatcherProcess(sender, e);
             watcherProcess.OnCompleted += new Completed(WatcherProcess_OnCompleted);
             watcherProcess.OnCreated += new FileSystemEventHandler(WatcherProcess_OnCreated);
             Thread threadDeal = new Thread(watcherProcess.Process);
             threadDeal.Start();
         }
         private void WatcherProcess_OnCreated( object sender, FileSystemEventArgs e)
         {
             OnCreated(sender, e);
         }
         private void fsWather_Deleted( object sender, FileSystemEventArgs e)
         {
             lock (hstbWather)
             {
                 hstbWather.Add(e.FullPath, e);
             }
             WatcherProcess watcherProcess = new WatcherProcess(sender, e);
             watcherProcess.OnCompleted += new Completed(WatcherProcess_OnCompleted);
             watcherProcess.OnDeleted += new FileSystemEventHandler(WatcherProcess_OnDeleted);
             Thread tdDeal = new Thread(watcherProcess.Process);
             tdDeal.Start();
         }
         private void WatcherProcess_OnDeleted( object sender, FileSystemEventArgs e)
         {
             OnDeleted(sender, e);
         }
         private void fsWather_Changed( object sender, FileSystemEventArgs e)
         {
             if (e.ChangeType == WatcherChangeTypes.Changed)
             {
                 if (hstbWather.ContainsKey(e.FullPath))
                 {
                     WatcherChangeTypes oldType = ((FileSystemEventArgs)hstbWather[e.FullPath]).ChangeType;
                     if (oldType == WatcherChangeTypes.Created || oldType == WatcherChangeTypes.Changed)
                     {
                         return ;
                     }
                 }
             }
             lock (hstbWather)
             {
                 hstbWather.Add(e.FullPath, e);
             }
             WatcherProcess watcherProcess = new WatcherProcess(sender, e);
             watcherProcess.OnCompleted += new Completed(WatcherProcess_OnCompleted);
             watcherProcess.OnChanged += new FileSystemEventHandler(WatcherProcess_OnChanged);
             Thread thread = new Thread(watcherProcess.Process);
             thread.Start();
         }
         private void WatcherProcess_OnChanged( object sender, FileSystemEventArgs e)
         {
             OnChanged(sender, e);
         }
         public void WatcherProcess_OnCompleted( string key)
         {
             lock (hstbWather)
             {
                 hstbWather.Remove(key);
             }
         }
     }
}

 使用了线程安全的Hashtable来处理一次改变触发两次事件的问题,要注意的是在实际项目使用中,在通过监控文件事情触发时开一个线程WatcherProcess去处理自己业务逻辑的时候,不管业务逻辑成功或者失败(例如有异常抛出一定要try一下)一定要让WatcherProcess Completed也就是MyFileSystemWatherWatcherProcess_OnCompleted执行去移除对应变化文件的Hashtablekey,不然下次此文件改变时是无法触发你的业务逻辑的。

    

     还有就是在进行文件监控的时候, 被监控文件在写入的时候,是会有I/O冲突的,即使写入文件是FileShare.Read的也会出现,要真正解决貌似只有FileMaping方法,但是我的项目中文本的写入软件不是我们能控制的,所以只有用处理异常的方法来解决。


轉自:http://www.cnblogs.com/zhaojingjing/archive/2011/01/21/1941586.html

这篇关于谈谈C#文件监控对象FileSystemWatcher使用感受的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/318887

相关文章

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

Java中的抽象类与abstract 关键字使用详解

《Java中的抽象类与abstract关键字使用详解》:本文主要介绍Java中的抽象类与abstract关键字使用详解,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、抽象类的概念二、使用 abstract2.1 修饰类 => 抽象类2.2 修饰方法 => 抽象方法,没有