2025년, 코딩은 선택이 아닌 필수!

2025년 모든 학교에서 코딩이 시작 됩니다. 먼저 준비하는 사람만이 기술을 선도해 갑니다~

강의자료/C#

[C#] FileSystemWatcher를 이용한 파일 모니터 구현

원당컴퓨터학원 2020. 12. 31. 08:41
목표

- FileSystemWatcher의 이벤트와 속성을 이해한다.

- 파일을 다루는 방법을 배운다.

- Splitter 사용법을 배운다

 

컴포넌트 설명

FileSystemWatcher : 파일시스템 속성 변경을 확인 할 수 있는 컴포넌트

DirectoryInfo : 디렉토리의 파일과 속성을 가져 올 수 있는 컴포넌트

Splitter : 화면을 분리해 주는 컴포넌트로 분리된 사이즈의 크기를 조정할때 사용됨

 

폼구성

위와 같이 화면 구성하자.

사용된 컴포넌트

상단 : Panel 안에 label,textBox,Button

하단 : groupbox 2개,splitter 1개 , 왼쪽 groupbox 의 Dock 속성을 left, 오를쪽 groupbox 의 속성을 Client 로 설정

왼쪽 groupbox : ListView - Columns 에 헤더 등록 및 View를 Details 로 설정

오른쪽 groupbox : 상단 panel(label 2개,TextBox 1개,ComboBox 1개,Button 2개) , 하단 ListBox

기타 : folderBrowserDialog,saveFileDialog,contextMenuStrip

 

소스코드 구현

1. 경로 버튼을 클릭 했을때 해당 폴더를 선택 후 파일 탐색기에 파일 보기 구현

-쓰레드에서 파일보기(FileView) 구현을 실행 시킨다.

1
2
3
4
5
6
7
8
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.listView1.Items.Clear();
                this.txtPath.Text = this.folderBrowserDialog1.SelectedPath;
 
                threadFileView = new Thread(new ParameterizedThreadStart(FileView));
                threadFileView.Start(this.folderBrowserDialog1.SelectedPath); ///선택된 디렉토리를 매개변수로 넘기자.
            }
cs

- FileView 코드 : 속성을 전체 혹은 숨김파일 제외 속성에 따라 파일 목록을 읽어 와서 OnFile Delegate 에 내용을 전달하여 OnFile 에서 리스트뷰에 뿌려주는 역할을 수행하고 하위디렉토리는 다시 들어가서 똑같은 작업을 반복 수행하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
        private void FileView(object dir)
        {
            DirectoryInfo di = new DirectoryInfo((string)dir);
            DirectoryInfo[] dti = di.GetDirectories();
 
            foreach (var f in di.GetFiles())
            {
                if (HiddenFile == true//전체 파일을 모두 조회한다.
                {
                    Invoke(OnFile, f.Name, f.Length.ToString(),
                        f.CreationTime.ToString());
                }
                else
                {
                    if (!f.Attributes.ToString().Contains(FileAttributes.Hidden.ToString())) // 속성이 숨김파일이 아닐 때만 조회한다.
                    {
                        Invoke(OnFile, f.Name, f.Length.ToString(),
                            f.CreationTime.ToString());
                    }
                }
            }
 
            for (int i = 0; i < di.GetDirectories().Length; i++///하위 디렉토리 파일을 조회 하자.
            {
                try
                {
                    FileView(dti[i].FullName);
                }
                catch
                {
                    continue;
                }
            }
        }
cs

-OnFile 델리게이트 생성 및 구현

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
        Thread threadFileView = null//파일조회 스레드 개체 생성
        private delegate void OnDelegateFile(string fn, string fl, string fc);
        private OnDelegateFile OnFile = null//델리게이트 생성
        bool HiddenFile = true//전체 조회, False 일때는 숨김파일이 아닌경우만 조회
 
        private void Form1_Load(object sender, EventArgs e)
        {
            OnFile = new OnDelegateFile(ListViewAdd); //OnFile 델리게이트에서 ListViewAdd를 실행시키자.
        }
 
        private void ListViewAdd(string fn, string fl, string fc) //리스트뷰에 들어온 데이터를 추가하자 
        {
            string fSize = GetFileSize(Convert.ToDouble(fl));
            this.listView1.Items.Add(new ListViewItem(new string[] { fn, fc, fSize }));
        }
 
        private string GetFileSize(double byteCount) //파일사이즈를 Bytes,KB,MB,GB 단위로 표현하자.
        {
            string size = "0 Bytes";
            if (byteCount >= 1024 * 1024 * 1024)
                size = String.Format("{0:##.##}", byteCount / (1024 * 1024 * 1024)) + " GB";
            else if (byteCount >= 1024 * 1024)
                size = String.Format("{0:##.##}", byteCount / (1024 * 1024)) + " MB";
            else if (byteCount >= 1024)
                size = String.Format("{0:##.##}", byteCount / 1024+ " KB";
            else if (byteCount > 0 && byteCount < 1024.0)
                size = byteCount.ToString() + " Bytes";
 
            return size;
        }
 
cs

 

- 파일 모니터 구현 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
        private FileSystemWatcher Watcher;
        private bool let = false//더블 모니터 방지
        private delegate void DelegateCreateListBoxItem(string EventName, string DateTime, string FilePath); //델리게이트 선언
 
        private void btnMonitor_Click(object sender, EventArgs e)
        {
            if (this.txtPath.Text == ""return;
 
            if (this.btnMonitor.Text == "모니터 ON")
            {
                this.btnMonitor.Text = "모니터 OFF";
                this.btnSave.Enabled = false;
 
                Watcher = new FileSystemWatcher();
                Watcher.Filter = "*." + this.txtExtension.Text.ToLower();
                Watcher.Path = Environment.ExpandEnvironmentVariables(this.txtPath.Text);
 
                if (this.cbMonitor.Text == "ON")
                    Watcher.IncludeSubdirectories = true;
                else
                    Watcher.IncludeSubdirectories = false;
 
                Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                        | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                Watcher.Changed += new FileSystemEventHandler(OnChanged);
                Watcher.Created += new FileSystemEventHandler(OnCreated);
                Watcher.Deleted += new FileSystemEventHandler(OnDeleted);
                Watcher.Renamed += new RenamedEventHandler(OnRenamed);
 
                Watcher.EnableRaisingEvents = true;
            }
            else
            {
                if (Watcher != null)
                {
                    Watcher.Changed -= new FileSystemEventHandler(OnChanged);
                    Watcher.Created -= new FileSystemEventHandler(OnCreated);
                    Watcher.Deleted -= new FileSystemEventHandler(OnDeleted);
                    Watcher.Renamed -= new RenamedEventHandler(OnRenamed);
 
                    Watcher.EnableRaisingEvents = false;
                }
                this.btnMonitor.Text = "모니터 ON";
                this.btnSave.Enabled = true;
            }
 
        }
 
        private void OnRenamed(object sender, RenamedEventArgs e)
        {
            CreateListBoxItem("Renamed", DateTime.Now.ToString(), e.FullPath);
        }
 
        private void OnDeleted(object sender, FileSystemEventArgs e)
        {
            CreateListBoxItem("Deleted", DateTime.Now.ToString(), e.FullPath);
        }
 
        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            CreateListBoxItem("Created", DateTime.Now.ToString(), e.FullPath);
        }
 
        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (let == false)
            {
                let = true;
                CreateListBoxItem("Changed", DateTime.Now.ToString(), e.FullPath);
            }
            else
            {
                let = false;
            }
        }
 
        private void CreateListBoxItem(string EventName, string DateTime, string fullPath)
        {
            if (this.lbLog.InvokeRequired)
            {
                DelegateCreateListBoxItem DelView = new DelegateCreateListBoxItem(InvokedCreateListViewItem);
                Invoke(DelView, new object[3] { EventName, DateTime, fullPath });
            }
            else
            {
                InvokedCreateListViewItem(EventName, DateTime, fullPath);
            }
        }
 
        private void InvokedCreateListViewItem(string eventName, string dateTime, string fullPath)
        {
            this.lbLog.Items.Add(eventName + " : (" + dateTime + ") : " + fullPath);
        }
 
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string savepath = this.saveFileDialog1.FileName;
 
                StreamWriter sw = new StreamWriter(savepath);
                foreach (string s in this.lbLog.Items)
                {
                    sw.WriteLine(s);
                }
                sw.Close();
            }
        }
    }
cs

 

- FileSystemWatcher  이벤트 속성

1) Changed : 지정된 Path에서 파일이나 디렉토리가 변경될때 발생

2) Created : 파일이나 디렉토리가 생성될때 발생

3) Deleted : 파일이나 디렉토리 삭제될때 발생

4) Renamed : 디렉토리나 파일 이름이 변경될때 발생

 

- NotifyFilter (조사할 내용 형식)

1) Attributes : 파일 또는 폴더의 특성

2) CreationTime : 파일이나 폴더를 만든시간

3) DirectoryName: 디렉터리의 이름

4) FileName : 파일의 이름

5) LastAccess : 파일 또는 폴더를 마지막으로 연 날짜

6) LastWrite : 파일 또는 폴더를 마지막으로 접근한 날짜

7) Security : 파일 또는 폴더의 보안설정

8) Size : 파일 또는 폴더의 크기

 

 

 

활용

파일의 변경 상태를 모니터링 하면서 변경된 파일을 백업기능 등을 구현 할 수 있다.

 

FileManager.zip
0.05MB

 

 

 

=====================================================

이 자료는 학생들과 특강시간에 만들어 보는 프로젝트입니다.

=====================================================

 

오늘도 최선을 다하는 우리 학생들을 응원합니다.

인천 서구 검단신도시 원당컴퓨터학원

 

 

사업자 정보 표시
원당컴퓨터학원 | 기희경 | 인천 서구 당하동 1028-2 장원프라자 502호 | 사업자 등록번호 : 301-96-83080 | TEL : 032-565-5497 | Mail : icon001@naver.com | 통신판매신고번호 : 호 | 사이버몰의 이용약관 바로가기