日期:2014-05-17  浏览次数:20961 次

C# 监视目录动作

哈哈,大早上的就写文章不好啊。

因为上班晚的缘故,所以早上都很有时间,这些时间也要利用一下,所以那,就做了一下C#的目录监视的功能,很强大。

下面就给大家演示一下

?

我用的是main函数写的,大家也可以用Form啊什么的做个很漂亮的界面什么的都行,方法是大家的,但原理就是如下这个。

static void Main(string[] args)
        {
            try
            {
                if (args.Length != 1)
                {
                    Console.WriteLine("usage: Watcher.exe(directory)");
                    Console.ReadKey();
                    return;
                }
                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = args[0];
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                watcher.Filter = "*.txt";
                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnChanged);
                watcher.Deleted += new FileSystemEventHandler(OnChanged);
                watcher.Renamed += new RenamedEventHandler(OnRenamed);
                watcher.EnableRaisingEvents = true;
                Console.WriteLine("Press \'q\' to quit the sample.");
                while (Console.Read() != 'q')
                {
                    ;
                }
            }
            catch (Exception e)
            {
                Console.ReadKey();
            }
            Console.ReadKey();

            
        }

?以上是主函数内操作

还有两个事件要实装

下面就给出来

        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("File :{0} renamed to {1}",e.OldFullPath,e.FullPath);
        }

?这个就是动作

?

好了 那么我们就实践一下把

很强大啊

?

?