2012-03-07 67 views
0

在此先感謝,對於大多數人來說毫無疑問很容易,但我是編程新手。如何繼續觀看目錄,直到按下退出按鈕?

我的第一個應用程序是一個winform應用程序,允許用戶選擇一個目錄,當他們點擊開始時,FileSystemWatcher被初始化。所有的作品和我已經處理了更改,刪除等,但我的問題是,它只處理一個事件(雖然正確),但之後它關閉。

我需要設置

Watcher.EnableRaisingEvents=True

直到退出按鈕被按下?

下面的代碼是目前:

public void btnStart(object sender, EventArgs e) 
    { 
     //create watcher and set properties 

     FileSystemWatcher Watcher1 = new FileSystemWatcher(); 

     Watcher1.Path = txtBoxDirToWatch.Text; 

     if (Watcher1.Path.Length <2) 
     { 
      MessageBox.Show("Path does not exist, Please reselect"); 
      return; 
     } 

     //user response to close 
     MessageBox.Show("Your directory is now being monitored for changes"); 

     Watcher1.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; 

     //watch all files in the path 

     Watcher1.Filter = "*.*"; 

     //add event handlers 

     Watcher1.Changed += new FileSystemEventHandler(OnChanged); 
     Watcher1.Created += new FileSystemEventHandler(OnChanged); 
     Watcher1.Deleted += new FileSystemEventHandler(OnDeleted); 
     Watcher1.Renamed += new RenamedEventHandler(OnRenamed); 

     //begin watching 

     Watcher1.EnableRaisingEvents = true;  

    } 

    public static void OnChanged(object source, FileSystemEventArgs e) 

    { 

     //need something in here to deal with changes and copy to hidden directory 

     string destination = Path.Combine(@"C:\Watcher\sync", e.Name); 

     File.Copy(e.FullPath, destination); 

    } 

    public static void OnRenamed(object source, FileSystemEventArgs e) 
    { 

然後我處理onrenamed,ondeleted等

誰能給一個推在正確的方向嗎?

感謝

+1

請張貼出觀察者是如何創建的代碼,處理程序等方面有許多可能的原因,可能失敗。有了上下文,我們可以更有幫助。 – Opsimath 2012-03-07 16:51:46

+0

對不起@DavidFerguson我以爲我原來添加了代碼,謝謝 – liammcdee 2012-03-09 17:16:03

回答

0

這裏的解決方案是爲每一個在程序啓動一個新的線程,並設置EnableRaisingEvents =新上的每個。

new Thread(ReNamed).Start(); new Thread(Changed).Start(); new Thread(Deleted).Start(); new Thread(Created).Start();

void ReNamed() 
    { 
     FileSystemWatcher Watcher2 = new FileSystemWatcher(); 

     Watcher2.Path = txtBxDirToWatch.Text; 
     Watcher2.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;// | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName; 

     //watch all files in the path 

     Watcher2.Filter = "*.*"; 

     //dont watch subdirectories as default 
     Watcher2.IncludeSubdirectories = false; 
     if (chkBxIncSub.Checked) 
     { 
     Watcher2.IncludeSubdirectories = true; 
     } 

     Watcher2.Renamed += new RenamedEventHandler(OnRenamed); 
     Watcher2.EnableRaisingEvents = true; 
    } 
相關問題