当前位置: 移动技术网 > IT编程>开发语言>c# > C#采用FileSystemWatcher实现监视磁盘文件变更的方法

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

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文实例讲述了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#程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网