2010-04-26 2 views

답변

19

FSW가 여러 폴더를 모니터링하는 것을 지원하지 않는다고 생각하므로 모니터링 할 폴더 당 하나만 인스턴스화하십시오. 당신은 같은 방법으로 이벤트 처리기를 가리킬 수 있지만, 원하는대로 작동해야합니다.

0

각 디렉토리에 하나씩 FileSystemWatcher의 인스턴스를 여러 개 사용할 수 있습니까?

12

가장 쉬운 방법은 FileSystemWatcher 개체의 인스턴스를 여러 개 만드는 것입니다.

http://www.c-sharpcorner.com/UploadFile/mokhtarb2005/FSWatcherMB12052005063103AM/FSWatcherMB.aspx

당신은 확실히 당신이 정확하게 두 폴더간에 이벤트를 처리 할 수 ​​있도록해야합니다 :

몇 가지 일반적인 차례 나오는, 파일 복사 또는 이동 등의 은 대응을하지 않지만 이벤트에 직접이 이벤트가 발생하면 이벤트는 발생합니다. 파일을 복사 할 때 시스템은 파일이 복사 된 디렉토리의 작성된 이벤트를 발생 시키지만 원래 디렉토리에 이벤트를 발생시키지 않습니다. 파일을 이동하면 서버는 소스 디렉토리에서 이벤트를 삭제하고 다음에 대상 디렉토리의 Created 이벤트를 발생시킵니다.

예를 들어, FileSystemWatcher의 이라는 두 인스턴스를 만듭니다. FileSystemWatcher1이 "C : \ My Documents"를보고, FileSystemWatcher2가 "C : \ Your Documents"를 보도록 설정되어 있습니다. 이제 의 파일을 "내 문서"에서 " 문서"로 복사하면 FileSystemWatcher2가 생성 한 이벤트는 이지만 FileSystemWatcher1의 경우 발생하는 이벤트는 이 아닙니다. 복사하는 것과 달리 파일이나 디렉토리를 이동하면 이벤트가 두 번 발생합니다. 앞의 예에서, 당신은 "내 문서"에서 파일을 이동 한 경우에 "문서"는 만든 이벤트가 FileSystemWatcher2에 의해 제기 될 수 및 삭제 된 이벤트 이

연결은 FileSystemWatcher

에 의해 제기 될 것이다 to FileSystemEventArgs

+0

내가 디렉토리를 모두 처리하기 위해 같은 방법을 사용할 수 있습니다, 아래의 예와 같이 말 : fileWatcher [인덱스] .Created + = 새 FileSystemEventHandler (OnCreated); 위의 경우 OnCreated()는 인덱스 값 (또는 모니터링해야하는 디렉토리)을 어떻게 알 수 있습니까? 감사. –

+0

@Bi 내가 당신이 묻는 것을 이해하면 (긴 날). 디렉터 정보는 FileSystemEventArs 매개 변수의 일부로 OnCreated 함수로 전달됩니다. http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs.aspx – kemiller2002

+0

Perfect - Thanks! –

3

FileSystemWatcher는 단일 상위 디렉터리 모니터링 만 지원합니다. 여러 형제 디렉토리를 모니터하려면 FileSystemWatcher의 여러 인스턴스를 작성해야합니다.

그러나 FileSystemWatcher의 하위 디렉터리 기능을 활용하면이 동작을 피할 수 있습니다. NTFS 연결 지점 (일명 심볼릭 링크)을보고있는 디렉토리의 하위 디렉토리로 만들 수 있습니다. Sysinternals 명성의 Mark Russinovich는 Junction이라는 유틸리티를 사용하여 심볼릭 링크를 쉽게 만들고 관리 할 수 ​​있습니다.

로컬 컴퓨터의 디렉터리에만 심볼릭 링크를 만들 수 있습니다.

1

FileSystemWatcher 개체의 인스턴스를 인스턴스화해야합니다. 이벤트를 동일한 메서드에 바인딩하고 보낸 사람 개체를 사용하여 FileSystemWatcher이 이벤트를 트리거했는지 확인할 수 있습니다.

 var fsw1 = new FileSystemWatcher(); 
     var fsw2 = new FileSystemWatcher(); 
     FileSystemEventHandler fsw_changed = delegate(object sender, FileSystemEventArgs e) 
     { 
      Console.WriteLine("{0} - {1}", (sender as FileSystemWatcher).Path, e.ChangeType); 
     }; 
     fsw1.Changed += fsw_changed; 
     fsw2.Changed += fsw_changed; 
0

또는이에서 같이 지켜 도메인의 특정 범위를 표시하는 데에 코드 경로를 통과 할 수있다 :이 도움이

multiple monitor link

희망.

+0

가리키는 링크는 각 경로에 대해 새 fsw 개체를 만듭니다. op가 요구하는 것이 아닙니다. –

2

비록 이것이 좋은 대답을 찾을 수 없기 때문에 나는이 대답을하기로 결심했습니다.

그럼, 목표는 FileSystemWatcher를 사용하여 여러 개의 하위 폴더 (하위 디렉토리 제외)를 모니터링하는 것이 었습니다. 여기 내 제안이다 :

using System; 
using System.IO; 
using System.Security.Permissions; 
using System.Collections.Generic; 

namespace MultiWatcher 
// ConsoleApplication, which monitors TXT-files in multiple folders. 
// Inspired by: 
// http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs(v=vs.100).aspx 

{ 
    public class Watchers 
    { 
     public static void Main() 
     { 
      Run(); 

     } 

     [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] 
     public static void Run() 
     { 
      string[] args = System.Environment.GetCommandLineArgs(); 

      // If a directory is not specified, exit program. 
      if (args.Length < 2) 
      { 
       // Display the proper way to call the program. 
       Console.WriteLine("Usage: Watcher.exe PATH [...] [PATH]"; 
       return; 
      } 
      List<string> list = new List<string>(); 
      for (int i = 1; i < args.Length; i++) 
      { 
       list.Add(args[i]); 
      } 
      foreach (string my_path in list) 
      { 
       Watch(my_path); 
      } 

      // Wait for the user to quit the program. 
      Console.WriteLine("Press \'q\' to quit the sample."); 
      while (Console.Read() != 'q') ; 
     } 
     private static void Watch(string watch_folder) 
     { 
      // Create a new FileSystemWatcher and set its properties. 
      FileSystemWatcher watcher = new FileSystemWatcher(); 
      watcher.Path = watch_folder; 
      /* Watch for changes in LastAccess and LastWrite times, and 
       the renaming of files or directories. */ 
      watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
       | NotifyFilters.FileName | NotifyFilters.DirectoryName; 
      // Only watch text files. 
      watcher.Filter = "*.txt"; 

      // Add event handlers. 
      watcher.Changed += new FileSystemEventHandler(OnChanged); 
      watcher.Created += new FileSystemEventHandler(OnChanged); 
      watcher.Deleted += new FileSystemEventHandler(OnChanged); 
      watcher.Renamed += new RenamedEventHandler(OnRenamed); 

      // Begin watching. 
      watcher.EnableRaisingEvents = true; 
     } 

     // Define the event handlers. 
     private static void OnChanged(object source, FileSystemEventArgs e) 
     { 
      // Specify what is done when a file is changed, created, or deleted. 
      Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); 
     } 

     private static void OnRenamed(object source, RenamedEventArgs e) 
     { 
      // Specify what is done when a file is renamed. 
      Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); 
     } 
    } 
} 
그래서
+3

FileWatcher는 IDisposable을 구현합니다. IDisposable.Dispose()가 프로그램을 종료하기 전에 더 이상 필요하지 않으면 (예 : 특정 감시 디렉토리가 삭제 된 경우) IDisposable.Dispose를 확인하는 패턴을 포함하면 제안 사항이 개선됩니다. –

관련 문제