9
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MacOS上で.NET Coreを使ってフォルダ/ファイル変更監視

Last updated at Posted at 2016-08-24

概要

MacOS上にてちょっとしたフォルダ監視のためにNode.jsをgrunt-contrib-watchするのが面倒だったので、愛するC#を使ってさくっと書いた。

Windowsなフォルダ監視コードは書いたことがあったのだが、本当にそれが.NETCoreで動くのかはやったことがなかったのでそういうテストも含んでいたりする。

.NET Coreについて

この辺りを読んで導入すべし。
http://qiita.com/koki_cheese/items/727577ab830a44050dcc

エディタはVSCodeを使い、C#なエクステンションを入れると幸せになれる。

やり方

新規プロジェクト作成

mkdir filewatcher
cd filewatcher
dotnet new

Program.csをカキカキ

using System;
using System.IO;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var watcher = new FileSystemWatcher();
            watcher.Path = args[0];
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
            
            var eventHandle = new FileSystemEventHandler((o,e)=>{
                Console.WriteLine("{0}: {1}", e.Name, e.ChangeType);
            });

            watcher.Changed += eventHandle;
            watcher.Created += eventHandle;
            watcher.Deleted += eventHandle;
            
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("監視開始");

            while(true){
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

実行

dotnet restore
dotnet run "watch dir path"

まとめ

良さ。

image

9
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?