프로그래밍/C#

[C#] FileSystemWatcher 폴더/파일변경관련 감시

ss-pro 2020. 10. 24. 22:16
반응형

이번에는 특정폴더에 파일이 복사되거나 변경하는 것을 감시하는 Class에 대해서 알아보겠습니다. FileSystemWatcher클래스를 사용하면 디렉토리 변경유무를 알수있습니다. 그럼 디렉토리 변경유무는 언제 체크가 필요할까요? 특정폴더를 감시해서 다른곳으로 파일을 전송하거나 아니면 파일이 생성될때 파일용량을 체크하여 자동삭제하도록 스케쥴을 걸때도 사용할수 있을것 같습니다. 이미지,동영상파일을 자동으로 FTP등을이용하여 클라우드서버에  전송하는 기능을 만들때에도 사용할수 있을것으로 보입니다. 

전체소스 : MSDN

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
 
 
//add namespace
using System.Security.Permissions;
using System.IO;                         // FileSystemWatcher
 
namespace FileSystemWatcherApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Run();
        }
 
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        private static void Run()
        {
            string[] args = 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 (directory)");
                return;
            }
 
            Console.WriteLine("Watcher directory:{0}", args[0]);
            // Create a new FileSystemWatcher and set its properties.
            using (FileSystemWatcher watcher = new FileSystemWatcher())
            {
                watcher.Path = args[1];
 
                // 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 = "*.*";
 
                // Add event handlers.
                watcher.Changed += OnChanged;
                watcher.Created += OnChanged;
                watcher.Deleted += OnChanged;
                watcher.Renamed += OnRenamed;
 
                // Begin watching.
                watcher.EnableRaisingEvents = true;
 
                // Wait for the user to quit the program.
                Console.WriteLine("Press 'q' to quit the sample.");
                while (Console.Read() != 'q') ;
            }
        }
 
        // 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: {e.OldFullPath} renamed to {e.FullPath}");
        }
    }
}

프로그램을 실행해보도록 하겠습니다. 프로그램을 실행하여 c:\Temp파일에 파일을 복사,수정,삭제시에는 아래와 같이 이벤트가 감지되는것을 확인할수 있습니다. 


출처
docs.microsoft.com/ko-kr/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1

반응형