FROM ME TO YOU

oh my bizarre life !!

FileSystemWatcherを使って特定フォルダの監視(シングルスレッド)

これまた仕事でよく使う「特定フォルダを監視してファイルが生成されたら何らかのアクションを行う」という機能を実装してみた。

まぁ「何らかのアクション」って書きましたけど、「テキストファイルをDBに取り込む」のが大半なんですけどねw

とりあえずファイルの生成アクションは下記で取得可能らしい。

FileSystemWatcher.NotifyFilter = NotifyFilters.FileName

本来はWindowsFormアプリケーションで実装すべきなんだけど、マルチスレッドプログラミングの知識が必要らしいので今回はここまで。

FileSystemWatcher クラス (System.IO)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;    // 追加

namespace FileSystemWatcherTest
{
    class Program
    {
        static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"C:\tmp";
            watcher.Filter = "*.csv";
            watcher.IncludeSubdirectories = false;
            
            //watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
            //                        | NotifyFilters.FileName | NotifyFilters.DirectoryName;

            watcher.NotifyFilter = NotifyFilters.FileName;  // ファイルの生成ならこれだけでよい

            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.Deleted += new FileSystemEventHandler(OnDeleted);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            watcher.EnableRaisingEvents = true;
            Console.WriteLine(watcher.Path + "を監視中...");
            Console.ReadKey();

        }

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("Rename: " + e.FullPath + " " + e.ChangeType);
        }


        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Delete: " + e.FullPath + " " + e.ChangeType);
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Create: " + e.FullPath + " " + e.ChangeType);
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Change: " + e.FullPath + " " + e.ChangeType);
        }

    }
}