C# でファイルを検索する簡単なプログラムを作成してみました。
Visual Studio 2010 で作成したので .NET Framework 4.0 で動作確認はしています。 MSDN のサンプルにあった、LINQ を使っていますので Visual Studio 2008/.NET Framework 3.5 以上です。
using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.IO; namespace FindFiles { class FindFiles { private int depthLevel = -1; public int DepthLevel { get { return depthLevel; } set { depthLevel = value; } } /// <summary> /// ファイル・フォルダの探索 /// <param name="curFolder">ファイルを検索するフォルダ</param> /// <param name="curDepth">現探索レベル</param> /// </summary> void FindFilesRecurse(string curFolder, int curDepth) { // まず、現フォルダ内のファイルを検索 try { IEnumerable<string> files = from file in Directory.EnumerateFiles(curFolder, "*") // メモ: LINQ ここで WHERE 句で絞り込める // where file.ToLower().StartsWith("something") // または、 where file.ToLower().Contains("something") select file; foreach (string file in files) { // 検索したファイルに対して何かする Console.WriteLine(file); } } catch (Exception e) { } // 次に、探索のレベル指定により if (DepthLevel == -1 || DepthLevel > curDepth) { try { // 現フォルダ内のサブフォルダを検索 IEnumerable<string> folders = from folder in Directory.EnumerateDirectories(curFolder, "*", SearchOption.TopDirectoryOnly) select folder; foreach (string f in folders) { // フォルダ再帰探索 FindFilesRecurse(f, curDepth + 1); } } catch (Exception e) { } } } /// <summary> /// メイン /// </summary> static void Main(string[] args) { if (args.Length >= 2) { FindFiles ff = new FindFiles(); // 検索開始フォルダ string folder = args[0]; // 探索するフォルダの深さ int depth = int.Parse(args[1]); if (depth < 0) depth = -1; ff.DepthLevel = depth; // 指定のフォルダが存在すれば探索開始 string fullpath = System.IO.Path.GetFullPath(folder); if (System.IO.Directory.Exists(fullpath)) { ff.FindFilesRecurse(fullpath, 0); } } else { Console.WriteLine("使い方: FindFiles <"folder"> <level>"); Console.WriteLine(" folder: 検索するフォルダ"); Console.WriteLine(" level: 検索するフォルダの深さ"); Console.WriteLine(" 例: FindFiles c:Temp -1 --- すべてのサブフォルダを検索"); Console.WriteLine(" 例: FindFiles c:Temp 0 --- 指定のフォルダのみ検索"); Console.WriteLine(" 例: FindFiles c:Temp 3 --- 3階層までのフォルダ検索"); } } } }