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

 

샘플코드

using System;
using System.IO;

namespace Test {
    internal class Program {
        private static void Main(string[] args)
        {
        	// "/" 안됨. "\\"변경 해야함.
            path.Replace("/", "\\");
            var directory = Directory.GetCurrentDirectory();
            var Watcher = new Watcher();
            Watcher.Init(directory);

            Console.WriteLine("경로:" + directory);
            Console.WriteLine("'q' 입력시 종료");
            while (Console.Read() != 'q') ;
        }
    }
}

public class Watcher {
    private readonly FileSystemWatcher m_watcher = new FileSystemWatcher();
    public void Init(string path)
    {
        m_watcher.Path = path;

        // 변경 사항을 감시 타입
        m_watcher.NotifyFilter = NotifyFilters.LastAccess
                               | NotifyFilters.LastWrite
                               | NotifyFilters.FileName
                               | NotifyFilters.DirectoryName;

        // 감시 필터
        m_watcher.Filter = "*.txt";

        // 이벤트 등록
        m_watcher.Changed += OnChanged;
        m_watcher.Created += OnChanged;
        m_watcher.Deleted += OnChanged;
        m_watcher.Renamed += OnRenamed;

        // 구성 요소가 활성화되는지를 나타내는 값을 가져오거나 설정합니다.
        m_watcher.EnableRaisingEvents = true;
        // 지정된 경로 내에 있는 하위 디렉터리를 모니터링해야 하는지를 나타내는 값을 가져오거나 설정합니다.
        m_watcher.IncludeSubdirectories = true;
    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // 파일 변경, 생성, 삭제시 로직
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
    }
    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // 파일 이름이 변경시 로직
        Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
    }
}
출처: https://dlgnlfus.tistory.com/847 [게임 개발 일기장:티스토리]

 

실행 결과

반응형