using System;
using System.Collections.Generic;
using System.Text;
using System.IO;namespace WatchApplication
{
    class MyWatch
    {
        private FileSystemWatcher watcher;
        string path;
        public MyWatch(string path)
        {
            watcher = new FileSystemWatcher();
            this.path = path;
            this.InitializeWatch();
        }        private void InitializeWatch()
        {
            this.watcher.Path = this.path;
            this.watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            this.watcher.Filter = "*.txt";
            this.watcher.Changed += new FileSystemEventHandler(this.OnChanged);
            this.watcher.Created += new FileSystemEventHandler(this.OnChanged);
            this.watcher.Deleted += new FileSystemEventHandler(this.OnChanged);
            this.watcher.Renamed += new RenamedEventHandler(this.OnRenamed);
        }        public void StartWatch()
        {
            this.watcher.EnableRaisingEvents = true;
        }        private void OnChanged(object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        }        private void OnRenamed(object source, RenamedEventArgs e)
        {
            Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
        }
    }
}
下面程序入口:
public static void Main()
        {
            //Run();
            //  Invoke this sample with an arbitrary set of command line arguments.
            //String[] arguments = Environment.GetCommandLineArgs();
            //Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
            MyWatch mywatch = new MyWatch(@"C:\");
            mywatch.StartWatch();
        }
重命名C:\下的.TXT文件,控制台为什么没输出呢?

解决方案 »

  1.   

    貌似这句“mywatch.StartWatch();”执行完毕之后,整个程序就退出了呀,当然不会有什么作用。
      

  2.   

    你还是在WinForm中实现吧,因为WinForm中保留了一个Run,程序是还在运行之中的,而你的这个程序已经被退出了要不你家一条语句public static void Main()
            {
                //Run();
                //  Invoke this sample with an arbitrary set of command line arguments.
                //String[] arguments = Environment.GetCommandLineArgs();
                //Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
                MyWatch mywatch = new MyWatch(@"C:\");
                mywatch.StartWatch();while(true)
    {
    }
            }