본문으로 바로가기

[펌]C# FileSystemWatcher + delegate 활용

category .NET/C#.NET 2013. 12. 4. 11:44

FileSystemWatcher 클래스는 파일 시스템 변경 알림을 수신하면서 디렉토리 또는

디렉토리의 파일이 변경되면 이벤트를 발생시킵니다.

 

FileSystemWatcher fs = new FileSystemWatcher();//개체 생성

fs.Path = "Test"; //Test 폴더 감시

fs.NotifyFilter = NotifyFilters.FileName|NotifyFilters.DirectoryName; //파일 이름과 폴더 이름 감시

fs.Filter = ""//특정 파일 감시 ex)*.exe,(모두 감시"", *.*)

fs.Created += new FileSystemEventHandler(fs_Created); //조건에 해당하는 파일 및 폴더의 생성 이벤트 등록

fs.Deleted+=new FileSystemEventHandler(fs_Deleted); //조건에 해당하는 파일 및 폴더의 삭제 이벤트 등록

fs.EnableRaisingEvents = true//이벤트 활성화

 

testeventhandler += new mydele(Form1_testeventhandler);

 

 

속성

설명

Path

조사할폴더의경로를가져오거나설정

NotifyFilter

조사할변경내용형식을가져오거나설정

Filter

폴더에서 모니터닝할 파일을 결정하는데 사용되는 필터 문자열을 가져오거나 설정

EnableRaisingEvents

구성 요소가 활성화 되는지 여부를 나타내는 값을 가져오거나 설정

 

 

public partial class Form1 : Form

{

delegate void mydele(string path);

event mydele testeventhandler;

 

public Form1()

{

InitializeComponent();

InitWatcher();

}

 

private void InitWatcher()

{

FileSystemWatcher fs = new FileSystemWatcher();

fs.Path = "Test";//

fs.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;

fs.Filter = "";

fs.Created += new FileSystemEventHandler(fs_Created);

fs.Deleted += new FileSystemEventHandler(fs_Deleted);

fs.EnableRaisingEvents = true;

 

testeventhandler += new mydele(Form1_testeventhandler);

}

 

void fs_Deleted(object sender, FileSystemEventArgs e)

{

MakeMessage(e.FullPath, "삭íe제|");

}

 

void Form1_testeventhandler(string path)

{

listBox1.Items.Add(path);

}

 

 

 

void fs_Created(object sender, FileSystemEventArgs e)

{

MakeMessage(e.FullPath,"생성");

}

 

private void MakeMessage(string FullPath, string msg)

{

string path = string.Format("{0}\\{1}"Application.StartupPath, FullPath);

string extension = Path.GetExtension(path); //확장자 검사 폴더면 Null 반환

if (extension == string.Empty)

{

path = string.Format("{0} 폴더가 {1}되었습니다", path, msg);

}

else

{

path = string.Format("{0} 파일이 {1}되었습니다", path, msg);

}

listBox1.Invoke(testeventhandler, new object[] { path });

}

}

 

    

결과:

 

자료 펌 : http://ehdrn.tistory.com/127