C#에서 FileSystemWatcher를 사용하여 여러 폴더 (하위 디렉토리 제외)를 모니터링하는 가장 좋은 방법은 무엇입니까?FileSystemWatcher를 사용하여 여러 폴더 모니터링
답변
FSW가 여러 폴더를 모니터링하는 것을 지원하지 않는다고 생각하므로 모니터링 할 폴더 당 하나만 인스턴스화하십시오. 당신은 같은 방법으로 이벤트 처리기를 가리킬 수 있지만, 원하는대로 작동해야합니다.
각 디렉토리에 하나씩 FileSystemWatcher의 인스턴스를 여러 개 사용할 수 있습니까?
가장 쉬운 방법은 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 FileSystemEventArgsFileSystemWatcher는 단일 상위 디렉터리 모니터링 만 지원합니다. 여러 형제 디렉토리를 모니터하려면 FileSystemWatcher의 여러 인스턴스를 작성해야합니다.
그러나 FileSystemWatcher의 하위 디렉터리 기능을 활용하면이 동작을 피할 수 있습니다. NTFS 연결 지점 (일명 심볼릭 링크)을보고있는 디렉토리의 하위 디렉토리로 만들 수 있습니다. Sysinternals 명성의 Mark Russinovich는 Junction이라는 유틸리티를 사용하여 심볼릭 링크를 쉽게 만들고 관리 할 수 있습니다.
로컬 컴퓨터의 디렉터리에만 심볼릭 링크를 만들 수 있습니다.
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;
가리키는 링크는 각 경로에 대해 새 fsw 개체를 만듭니다. op가 요구하는 것이 아닙니다. –
비록 이것이 좋은 대답을 찾을 수 없기 때문에 나는이 대답을하기로 결심했습니다.
그럼, 목표는 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);
}
}
}
그래서
FileWatcher는 IDisposable을 구현합니다. IDisposable.Dispose()가 프로그램을 종료하기 전에 더 이상 필요하지 않으면 (예 : 특정 감시 디렉토리가 삭제 된 경우) IDisposable.Dispose를 확인하는 패턴을 포함하면 제안 사항이 개선됩니다. –
- 1. FileSystemWatcher를 사용하여 C# 폴더 연결을 따르십시오
- 2. Windows에서 filesystemwatcher를 사용하여 samba 공유 폴더/드라이브를 보는 방법은 무엇입니까?
- 3. FileSystemWatcher를 사용하여 디렉토리보기
- 4. JavaCard 모니터링 폴더
- 5. asp.net (C#)을 사용하여 FileSystemWatcher를 사용하는 방법
- 6. C# : FileSystemWatcher를 사용하여 파일을 복사하거나 이동
- 7. 여러 레일 어플리케이션 모니터링
- 8. 여러 폴더
- 9. Windows에서 파일/폴더 복사 작업 추적/모니터링
- 10. FileSystemWatcher - 대체 데이터 스트림 모니터링
- 11. C#의 파일/디렉토리 액세스 모니터링
- 12. EJB3를 사용하여 모니터링 빈
- 13. 여러 FileSystemWatchers를 사용하여 로컬 시스템의 파일을 모니터링 하시겠습니까?
- 14. 라이브 바인딩을 사용하여 목록 모니터링
- 15. 부두가있는 여러 개의 webroot 폴더
- 16. FileSystemWatcher를 사용하여 파일을 변경하는 프로세스를 식별 할 수 있습니까?
- 17. FileSystemWatcher를 사용하여 파일을 볼 때 파일을 삭제할 수 있습니까?
- 18. .Net을 사용하여 응용 프로그램 모니터링
- 19. ReadDirectoryChangesW API를 사용하여 디렉토리 모니터링
- 20. PHP를 사용하여 MySQL 데이터베이스 모니터링
- 21. 디렉토리 모니터링
- 22. Tomcat - 여러 개의 webapps 폴더
- 23. Google 리더의 여러 태그/폴더
- 24. 여러 개의 파일런 모니터링 응용 프로그램
- 25. 컴퓨터 클러스터에서 여러 Windows 서비스 인스턴스 모니터링
- 26. 호빗 모니터링 - 테스트 당 여러 개의 그래프?
- 27. C# FileSystemWatcher 잠금 폴더
- 28. VB.NET에서 FolderBrowserDialog 컨트롤을 사용하여 여러 폴더 경로를 선택하는 방법
- 29. DirectoryEntry를 사용하여 폴더 만들기
- 30. C를 사용하여 폴더 동기화
내가 디렉토리를 모두 처리하기 위해 같은 방법을 사용할 수 있습니다, 아래의 예와 같이 말 : fileWatcher [인덱스] .Created + = 새 FileSystemEventHandler (OnCreated); 위의 경우 OnCreated()는 인덱스 값 (또는 모니터링해야하는 디렉토리)을 어떻게 알 수 있습니까? 감사. –
@Bi 내가 당신이 묻는 것을 이해하면 (긴 날). 디렉터 정보는 FileSystemEventArs 매개 변수의 일부로 OnCreated 함수로 전달됩니다. http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs.aspx – kemiller2002
Perfect - Thanks! –