2013-01-01 46 views
0
class Program 
{ 
    FileSystemWatcher _watchFolder; 
    string sPath = @"D:\TestMonitor"; 
    static void Main(string[] args) 
    { 
     Program p = new Program(); 
     Thread t = new Thread(new ThreadStart(p.startActivityMonitoring)); 
     t.Start(); 
    } 


    private void startActivityMonitoring() 
    { 
     _watchFolder = new FileSystemWatcher(); 
     _watchFolder.Path = Convert.ToString(sPath); 
     _watchFolder.NotifyFilter = System.IO.NotifyFilters.DirectoryName; 
     _watchFolder.NotifyFilter = 
     _watchFolder.NotifyFilter | System.IO.NotifyFilters.FileName; 
     _watchFolder.NotifyFilter = 
     _watchFolder.NotifyFilter | System.IO.NotifyFilters.Attributes; 
     _watchFolder.Changed += new FileSystemEventHandler(eventRaised); 
     _watchFolder.Created += new FileSystemEventHandler(eventRaised); 
     _watchFolder.Deleted += new FileSystemEventHandler(eventRaised); 
     _watchFolder.Renamed += new System.IO.RenamedEventHandler(eventRaised); 
     _watchFolder.EnableRaisingEvents = true; 
    } 



    private void eventRaised(object sender, System.IO.FileSystemEventArgs e) 
    { 
     switch (e.ChangeType) 
     { 
      case WatcherChangeTypes.Changed: 
       Console.WriteLine(string.Format("File {0} has been modified\r\n", e.FullPath)); 

       break; 
      case WatcherChangeTypes.Created: 
       Console.WriteLine(string.Format("File {0} has been created\r\n", e.FullPath)); 

       break; 
      case WatcherChangeTypes.Deleted: 
       Console.WriteLine(string.Format("File {0} has been deleted\r\n", e.FullPath)); 

       break; 
      default: // Another action 
       break; 
     } 
    } 

} 

使用FileSystemWatcher的轮询的目录里面的变化,当我尝试登录使用Console.WriteLine它不工作,虽然改变的简单程序内工作。Console.WriteLine没有一个C#事件处理

不知道是什么原因造成这个问题,因为Console.WriteLine行之有效任何线程

+0

确定该事件被触发,该'Console.WriteLine'方法被调用? – Mir

+0

是它被调用 – muddassir

回答

4

您的程序后马上退出内部开始线程。您需要保持程序运行。 一种简单的方法是使用Console.ReadLine来停止程序退出。

static void Main(string[] args) 
    { 
     Program p = new Program(); 
     Thread t = new Thread(new ThreadStart(p.startActivityMonitoring)); 
     t.Start(); 
     Console.Writeline("Press enter to exit"); 
     Console.ReadLine(); 
    } 

enter image description here

+0

遗憾错过Console.WriteLine()时,我复制的代码:(。实际的问题是,虽然我能看到升起Console.WriteLine不登录到控制台 – muddassir

+1

你缺少控制台事件.ReadLine,它会让程序等待? – Ngm