header
CodePanic! > C#.NET Tips > 今ここ

■ファイルシステムを監視する(ファイルの作成監視例)

FileSystemWatcherコンポーネントを利用します。
Formにドラッグ&ドロップするだけで
ファイルシステムを監視し、ファイルの更新や作成を知ることができます。

例ではCドライブ以下をすべて監視し、
ファイルが作成されたらそれを捕捉、ファイル名のフルパスを出力パネルに表示します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            fileSystemWatcher1.Created +=new System.IO.FileSystemEventHandler(fileSystemWatcher1_Created);

            // 監視対象フォルダ
            fileSystemWatcher1.Path = @"c:\";

            // すべてのファイルを監視
            fileSystemWatcher1.Filter = "*.*";

            // サブディレクトリも監視に含める
            fileSystemWatcher1.IncludeSubdirectories = true;

            // 監視の種類を設定(複数組み合わせも可)
            fileSystemWatcher1.NotifyFilter = System.IO.NotifyFilters.FileName;

            // 監視有効
            fileSystemWatcher1.EnableRaisingEvents = true;
        }

        private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            // ファイルを作成したりコピーしたりするとフルパスで出力されます
            System.Diagnostics.Debug.WriteLine(e.FullPath);
        }
    }
}




Copyright © 2008.07 - shougo suzaki