C#采用FileSystemWatcher实现监视磁盘文件变更的方法

本文实例讲述了C#采用FileSystemWatcher实现监视磁盘文件变更的方法。分享给大家供大家参考。具体实现方法如下:

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

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

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

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

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

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

使用方法:

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

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

源代码如下:


namespace FileSystemWatcherDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            //watcher组

            FileSystemWatcher[] watchers;

            //若未传递参数,则监视所有文件系统,包括CD-ROM(不可用),可移动磁盘(不可用)等             if (args.Length == 0)             {                 string[] drivers = Directory.GetLogicalDrives();                 watchers = new FileSystemWatcher[drivers.Length];

                for (int i = 0; i < drivers.Length; i++)                 {                     try                     {                         watchers[i] = new FileSystemWatcher { Path = drivers[i] };                     }                     catch (Exception ex)                     {                         Trace.TraceWarning(ex.Message);                     }                 }             }             else             {                 watchers = new FileSystemWatcher[1];                 watchers[0] = new FileSystemWatcher { Path = args[0] };             }

            foreach (FileSystemWatcher w in watchers)             {                 if (w == null) continue;

                w.Filter = "*";                 w.IncludeSubdirectories = true;                 w.EnableRaisingEvents = true;

                w.Created += onFileSystem_Changed;                 w.Deleted += onFileSystem_Changed;                 w.Changed += onFileSystem_Changed;                 w.Renamed += watcher_Renamed;             }

            Console.ReadLine();         }

        #region [ 检测文件是否占用 ]         /// <summary>         /// 检测文件是否占用         /// </summary>         /// <param name="filename"></param>         /// <returns></returns>         static bool IsFileReady(string filename)         {             var fi = new FileInfo(filename);             FileStream fs = null;             try             {                 fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);                 return true;             }             catch (IOException)             {                 return false;             }

            finally             {                 if (fs != null)                     fs.Close();             }         }         #endregion

        private static volatile object _lock = true;         static void onFileSystem_Changed(object sender, FileSystemEventArgs e)         {             lock (_lock)             {                 Console.ForegroundColor = ConsoleColor.DarkGray;                 Console.Write("[");                 Console.Write(DateTime.Now.ToString("HH:mm:ss"));                 Console.Write("] ");

                switch (e.ChangeType.ToString().ToLower())                 {                     case "created":                         //while (!IsFileReady(e.FullPath))                         //{                         //    if (!File.Exists(e.FullPath))                         //        return;                         //    Thread.Sleep(100);                         //}                         Console.ForegroundColor = ConsoleColor.Green;                         Console.Write(e.ChangeType);                         Console.ForegroundColor = ConsoleColor.White;                         Console.Write(" ");                         Console.Write(e.Name);                         Console.Write(" ");                         Console.ForegroundColor = ConsoleColor.DarkGray;                         Console.Write(e.FullPath);

                        break;                     case "deleted":                         Console.ForegroundColor = ConsoleColor.Red;                         Console.Write(e.ChangeType);                         Console.ForegroundColor = ConsoleColor.White;                         Console.Write(" ");                         Console.Write(e.Name);                         Console.Write(" ");                         Console.ForegroundColor = ConsoleColor.DarkGray;                         Console.Write(e.FullPath);                         break;                     case "changed":                         Console.ForegroundColor = ConsoleColor.Cyan;                         Console.Write(e.ChangeType);                         Console.ForegroundColor = ConsoleColor.White;                         Console.Write(" ");                         Console.Write(e.Name);                         Console.Write(" ");                         Console.ForegroundColor = ConsoleColor.DarkGray;                         Console.Write(e.FullPath);                         break;                 }

                Console.Write("\r\n");             }         }         static void watcher_Renamed(object sender, RenamedEventArgs e)         {             Console.ForegroundColor = ConsoleColor.Magenta;             Console.Write(e.ChangeType);             Console.ForegroundColor = ConsoleColor.White;             Console.Write(" ");             Console.Write(e.OldName);             Console.Write(e.OldFullPath);             Console.ForegroundColor = ConsoleColor.Yellow;             Console.Write(" ");             Console.Write(e.Name);             Console.Write(e.FullPath);             Console.Write(Thread.CurrentThread.Name);             Console.Write("\r\n");         }     } }

希望本文所述对大家的C#程序设计有所帮助。