LoginSignup
9
13

More than 5 years have passed since last update.

階層が深いフォルダ内のファイル検索は EnumerateFiles メソッドが早い!

Last updated at Posted at 2017-06-12

はじめに

企業内のファイルサーバには多数のフォルダ・サブフォルダが作成されていますし、個人のパソコン内にもフォルダが複雑に作成されています。
.NET Framrwork では、サブフォルダ内のファイルも列挙してくれる System.IO.Directory.GetFiles(path, pattern, System.IO.SearchOption.AllDirectories) メソッドがありますが、こちらはすべてを列挙しつくすまでメソッドを抜けないため時間がかかりますし、一気に結果を返すので検索処理中にはメモリをそれなりに消費します。
.NET Framework 4.0 以降をアプリケーションで使用する場合、IEnumerable 型で返す System.IO.Directory.EnumerateFiles(path, pattern, System.IO.SearchOption.AllDirectories) を使うことで、前述の弱点を解消できます。

サンプルコード

指定のフォルダ内(サブフォルダを含む)から、サイズ 0 のファイルを3つ探します。

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var dtStart = DateTime.Now;
            System.IO.Directory.GetFiles("\\\\fileserver\\shared", "*.*", System.IO.SearchOption.AllDirectories)
                .Where(e => (new System.IO.FileInfo(e)).Length == 0)
                .Where(e => { Console.WriteLine(e); return true; })
                .Take(3).ToArray();
            var dtEnd = DateTime.Now;
            Console.WriteLine();
            Console.WriteLine("処理時間は " + (dtEnd - dtStart).TotalSeconds.ToString() + "秒");
            Console.Read();
        }
    }
}

結果の例

150GBバイト超ある共有フォルダを対象に、EnumerateFiles メソッドで検索させた結果...

p1.png

GetFiles メソッドを使用した場合...

pp.png

9
13
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
13