C# FileSystemWatcher 监视磁盘文件变更

简化需求:有一个简化了的需求是这样的:有一个拍照程序在运行,一旦抓拍之后则将图片文件存储至某目录,然后图片要上传至远程服务器并update数据库。

原需求:原先的需求是这样的:有一台PDA扫码枪,一个IP照相机放置在下线区传送带上方。当PDA扫描箱子上的条码,触发相机拍照,将图片流传至远端服务器,找到对应的条码,将图片存储并更新数据库。

然而我不知道PDA扫描的瞬间如何与IP相机通信(蓝牙或WLAN?),其实关键是我不知道怎样使用IP相机的外触发功能,增加蓝牙触发器?也不知道怎样hack或ssh到这个相机(应该是linux的吧),所以只能先使用简化需求的版本。

而简化需求的版本,关键就是监视文件夹内容变化与上传文件流。

昨天问了下度娘,C#中的监视组件名字叫做FileSystemWatcher。

于是写了个demo,可以监视所有逻辑盘或者某个文件夹。

使用方法:

1.直接打开是监视所有逻辑磁盘文件变化。

2.或者传递参数,监视某一路径文件变化。如图,监视e盘

源代码:

  1 namespace FileSystemWatcherDemo
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 //watcher组
8 FileSystemWatcher[] watchers;
9
10 //若未传递参数,则监视所有文件系统,包括CD-ROM(不可用),可移动磁盘(不可用)等
11 if (args.Length == 0)
12 {
13 string[] drivers = Directory.GetLogicalDrives();
14 watchers = new FileSystemWatcher[drivers.Length];
15
16 for (int i = 0; i < drivers.Length; i++)
17 {
18 try
19 {
20 watchers[i] = new FileSystemWatcher { Path = drivers[i] };
21 }
22 catch (Exception ex)
23 {
24 Trace.TraceWarning(ex.Message);
25 }
26 }
27 }
28 else
29 {
30 watchers = new FileSystemWatcher[1];
31 watchers[0] = new FileSystemWatcher { Path = args[0] };
32 }
33
34 foreach (FileSystemWatcher w in watchers)
35 {
36 if (w == null) continue;
37
38 w.Filter = "*";
39 w.IncludeSubdirectories = true;
40 w.EnableRaisingEvents = true;
41
42 w.Created += onFileSystem_Changed;
43 w.Deleted += onFileSystem_Changed;
44 w.Changed += onFileSystem_Changed;
45 w.Renamed += watcher_Renamed;
46 }
47
48 Console.ReadLine();
49 }
50
51 #region [ 检测文件是否占用 ]
52 /// <summary>
53 /// 检测文件是否占用
54 /// </summary>
55 /// <param name="filename"></param>
56 /// <returns></returns>
57 static bool IsFileReady(string filename)
58 {
59 var fi = new FileInfo(filename);
60 FileStream fs = null;
61 try
62 {
63 fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);
64 return true;
65 }
66 catch (IOException)
67 {
68 return false;
69 }
70
71 finally
72 {
73 if (fs != null)
74 fs.Close();
75 }
76 }
77 #endregion
78
79 private static volatile object _lock = true;
80 static void onFileSystem_Changed(object sender, FileSystemEventArgs e)
81 {
82 lock (_lock)
83 {
84 Console.ForegroundColor = ConsoleColor.DarkGray;
85 Console.Write("[");
86 Console.Write(DateTime.Now.ToString("HH:mm:ss"));
87 Console.Write("] ");
88
89 switch (e.ChangeType.ToString().ToLower())
90 {
91 case "created":
92 //while (!IsFileReady(e.FullPath))
93 //{
94 // if (!File.Exists(e.FullPath))
95 // return;
96 // Thread.Sleep(100);
97 //}
98 Console.ForegroundColor = ConsoleColor.Green;
99 Console.Write(e.ChangeType);
100 Console.ForegroundColor = ConsoleColor.White;
101 Console.Write(" ");
102 Console.Write(e.Name);
103 Console.Write(" ");
104 Console.ForegroundColor = ConsoleColor.DarkGray;
105 Console.Write(e.FullPath);
106
107 break;
108 case "deleted":
109 Console.ForegroundColor = ConsoleColor.Red;
110 Console.Write(e.ChangeType);
111 Console.ForegroundColor = ConsoleColor.White;
112 Console.Write(" ");
113 Console.Write(e.Name);
114 Console.Write(" ");
115 Console.ForegroundColor = ConsoleColor.DarkGray;
116 Console.Write(e.FullPath);
117 break;
118 case "changed":
119 Console.ForegroundColor = ConsoleColor.Cyan;
120 Console.Write(e.ChangeType);
121 Console.ForegroundColor = ConsoleColor.White;
122 Console.Write(" ");
123 Console.Write(e.Name);
124 Console.Write(" ");
125 Console.ForegroundColor = ConsoleColor.DarkGray;
126 Console.Write(e.FullPath);
127 break;
128 }
129
130 Console.Write("\r\n");
131 }
132 }
133 static void watcher_Renamed(object sender, RenamedEventArgs e)
134 {
135 Console.ForegroundColor = ConsoleColor.Magenta;
136 Console.Write(e.ChangeType);
137 Console.ForegroundColor = ConsoleColor.White;
138 Console.Write(" ");
139 Console.Write(e.OldName);
140 Console.Write(e.OldFullPath);
141 Console.ForegroundColor = ConsoleColor.Yellow;
142 Console.Write(" ");
143 Console.Write(e.Name);
144 Console.Write(e.FullPath);
145 Console.Write(Thread.CurrentThread.Name);
146 Console.Write("\r\n");
147 }
148 }
149 }

仍有bug,望高手指正。

附上编译好的exe,可以直接运行。

 
 
标签: 文件监视

C# FileSystemWatcher 监视磁盘文件的更多相关文章

  1. C# FileSystemWatcher 监视磁盘文件变更

    简化需求:有一个简化了的需求是这样的:有一个拍照程序在运行,一旦抓拍之后则将图片文件存储至某目录,然后图片要上传至远程服务器并update数据库. 原需求:原先的需求是这样的:有一台PDA扫码枪,一个 ...

  2. 使用FileSystemWatcher监视指定目录

    使用 FileSystemWatcher 监视指定目录中的更改.可监视指定目录中的文件或子目录的更改. 以下是一个简单的实例,用来监控指定目录下文件的新增.删除.重命名等情况(文件内容更改会触发多次, ...

  3. FileSystemWatcher 监视指定目录中的变更

    .Net框架类库中的FileSystemWatcher如它的名称一样是一个用于监视文件系统变化的一个控件.使用 FileSystemWatcher 监视指定目录中的更改.可监视指定目录中的文件或子目录 ...

  4. 使用FileSystemWatcher监视文件变化

    本文转载:http://www.cnblogs.com/zanxiaofeng/archive/2011/01/08/1930583.html FileSystemWatcher基础 属性: Path ...

  5. 利用FileSystemWatcher实现磁盘文件监控

    马上放假了,好开森啊O(∩_∩)O哈哈~ ——————————————————————————————————————————————————————— 昨天逛园子,发现了一个FileSystemWa ...

  6. C#使用FileSystemWatcher控件实现的文件监控功能示例

    本文实例讲述了C#使用FileSystemWatcher控件实现的文件监控功能.分享给大家供大家参考,具体如下: FileSystemWatcher 可以使用FileSystemWatcher组件监视 ...

  7. 文件读写(二)利用SteamReader和StreamWrite类处理字符串、FileSystemWatcher、BinaryReader/BinaryWriter

    一.读写类: TextReader/TextWriter:文本读写,抽象类 TextReader,其派生类: StreamReader:以一种特定的编码从字节流中读取字符. StringReader: ...

  8. C#实现对文件目录的实时监控

    本文主要描述如何通过C#实现实时监控文件目录下的变化,包括文件和目录的添加,删除,修改和重命名等操作. 首先,我们需要对.net提供的FileSystemWatcher类有所了解.我有些懒,找了MSD ...

  9. grunt打包过程中的注意点

    1.安装nodeJS   nodeJS下载地址: http://www.nodejs.org/download/ 2.   在Node.js command prompt 这个控制面板输入 npm i ...

随机推荐

  1. SQL Server 2008 R2 性能计数器详细列表(四)

    原文:SQL Server 2008 R2 性能计数器详细列表(四) SQL Server Latches 对象: 监视称为闩锁的内部 SQL Server 资源锁.通过监视闩锁来确定用户活动和资源使 ...

  2. Docker安装应用程序(Centos6.5_x64)

    Docker安装应用程序(Centos6.5_x64) Authoer::jom_ch@2014/7/23 Docker官方网站 http://www.docker.com/ 一,安装EPEL 关于E ...

  3. redis和redis php扩展安装(转)

    redis是一个内存数据库,比memcache支持更丰富的value类型,新浪微博就使用redis来做缓存. redis的源码安装 wget http://download.redis.io/redi ...

  4. Linux Kernel系列 - 黄牛X内核代码凝视

    Hanks.Wang - 专注于操作系统与移动安全研究.Linux-Kernel/SELinux/SEAndroid/TrustZone/Encription/MDM    Mail - byhank ...

  5. php:的图形计算器的面向对象的版本武器2

    通过自带部分result.class.php分流,由于这三个类继承shape这个类,让我们来看看,面向对象的继承. shape.class.shape档 <?php abstract class ...

  6. NPOI以及在ASP.NET MVC中的使用

    NPOI以及在ASP.NET MVC中的使用 1.前言 相信大家在工作中经常要遇到一些导入导出Execl操作.学习贵在分享,分享使人快乐,园子里的前辈已经有很多好的文章,鄙人也是能力有限,在这里把这些 ...

  7. i++与++i哪个效率更高

    简单的比较前缀自增运算符和后缀自增运算符的效率是片面的, 因为存在很多因素影响这个问题的答案. 首先考虑内建数据类型的情况: 如果自增运算表达式的结果没有被使用, 而是仅仅简单地用于增加一元操作数, ...

  8. 设计模式之享元模式(Flyweight)摘录

    23种GOF设计模式一般分为三大类:创建型模式.结构型模式.行为模式. 创建型模式抽象了实例化过程,它们帮助一个系统独立于怎样创建.组合和表示它的那些对象.一个类创建型模式使用继承改变被实例化的类,而 ...

  9. dede织梦背景经常使用标签

    一些非常实用的标签调用的方法 关键描写叙述调用标签: <meta name="keywords" content="{dede:field name='keywor ...

  10. 经典算法题每日演练——第十六题 Kruskal算法

    原文:经典算法题每日演练--第十六题 Kruskal算法 这篇我们看看第二种生成树的Kruskal算法,这个算法的魅力在于我们可以打一下算法和数据结构的组合拳,很有意思的. 一:思想 若存在M={0, ...