FileSystemWatcher 는 특정 폴더 경로(디렉토리)의 모든 파일

파일이 생성되거나 변경되면 함수 호출을 해줍니다.

 

우선 사용법은

1. FileSystemWatcher 생성자 호출

2. 감시할 폴더 설정(디렉토리)

3. 감시할 항목들 설정 (파일 생성, 크기, 이름., 마지막 접근 변경등..)

4. 감시할 이벤트 설정 (생성, 변경, 삭제..)

5. FIleSystemWatcher 감시 모니터링 활성화

6. 감시할 폴더 내부 변경시 event 호출

 

위 내용을 코드로 구현하면 ...

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; // FileSystemWatcher 은 System.IO 안에 있습니다. using System.Windows.Forms; namespace WindowsFormsApplication { public class FileWatcher { string EqpDirPath = "D:\test\"; private void initWatcher() { watcher = new FileSystemWatcher(); //1. FileSystemWatcher 생성자 호출 watcher.Path = EqpDirPath; //2. 감시할 폴더 설정(디렉토리) // 3. 감시할 항목들 설정 (파일 생성, 크기, 이름., 마지막 접근 변경등..) watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastAccess | NotifyFilters.CreationTime | NotifyFilters.LastWrite; //감시할 파일 유형 선택 예) *.* 모든 파일 watcher.Filter = "*.*";

 

watcher.IncludeSubdirectories = true; // 4. 감시할 이벤트 설정 (생성, 변경..) watcher.Created += new FileSystemEventHandler(Changed); watcher.Changed += new FileSystemEventHandler(Changed); watcher.Renamed += new RenamedEventHandler(Renamed); // 5. FIleSystemWatcher 감시 모니터링 활성화 watcher.EnableRaisingEvents = true; } // 6. 감시할 폴더 내부 변경시 event 호출 private void Changed(object source, FileSystemEventArgs e) { MessageBox.Show(e.FullPath); } private void Renamed(object source, RenamedEventArgs e) { MessageBox.Show(e.FullPath); }

 

 

 

코드 상단 주석처럼  

FileSystemWatcher 은 using System.IO 를 선언해 주셔야 합니다.  

initWatcher() 함수를 실행시키면  

주석 번호대로 1~ 5번까지 initWatcher() 함수가 실행이 된 상태에서  

D:\test\ 해당 파일 경로에 파일 또는 폴더가 생기면 바로 Changed() 이벤트가 호출됩니다.  

호출될때 담겨지는 파라미터 FileSystemEventArgs e 에서 e.Fullpath 를 꺼내오면 

생성된 파일의 전체 경로를 가져 옵니다. 

  예) D:\test\새 텍스트 문서.txt  

이렇게 FileSystemWatcher 를 사용해서 해당 폴더를 실시간으로 감지 모니터링하는 기능을 구현 했습니다.  

 

다음 포스팅에선 이렇게 폴더를 감지해서  

FTP 파일 서버로 업로드까지 확장시켜 볼게요 

 

 

 

+ Recent posts