カレントフォルダ(と、そのサブフォルダ)から、目的のファイルを検索し、別なフォルダにコピーしたり移動したりしてまとめます。
オプションでコピー・移動を選択したり、再帰的に検索するかどうかを指定したりできます。
使い方: ExtractFiles.exe [パターン] [コピー先ディレクトリ] /m /r ※検索対象はカレントディレクトリです。 ※パターンにはワイルドカードが使えます。 ※コピー先ディレクトリが存在しない場合、自動的に作成されます。 /m ファイルをコピーではなく移動させます。 /r サブディレクトリも再帰的に検索します。
using System; using System.IO; namespace ExtractFiles { class Program { static void Main(string[] args) { if (args.Length < 2) { Usage(); } else { string token = args[0]; string destDirectory = args[1]; bool move = false; bool recursive = false; for (int i = 2; i < args.Length; i++) { string option = args[i].ToLower(); if (option == "/m") { move = true; } if (option == "/r") { recursive = true; } } DoExtract(token, destDirectory, move, recursive); } } static void DoExtract(string token, string destDirectory, bool move, bool recursive) { if (!Directory.Exists(destDirectory)) { Directory.CreateDirectory(destDirectory); } string srcDirectory = System.Environment.CurrentDirectory; string[] files = null; if (recursive) { files = Directory.GetFiles(srcDirectory, token, SearchOption.AllDirectories); } else { files = Directory.GetFiles(srcDirectory, token, SearchOption.TopDirectoryOnly); } if (files.Length == 0) { Console.WriteLine("見つかりませんでした。"); } else { foreach (string srcPath in files) { string destPath = destDirectory + "\\" + Path.GetFileName(srcPath); int count = 1; while (File.Exists(destPath)) { destPath = destDirectory + "\\" + Path.GetFileNameWithoutExtension(srcPath) + "_" + count.ToString() + Path.GetExtension(srcPath); count++; } if (move) { Console.WriteLine("【移動】{0}\r\n→{1}", srcPath, destPath); File.Move(srcPath, destPath); } else { Console.WriteLine("【コピー】{0}\r\n→{1}", srcPath, destPath); File.Copy(srcPath, destPath); } } } } static void Usage() { Console.WriteLine("使い方: ExtractFiles.exe [パターン] [コピー先ディレクトリ] /m /r"); Console.WriteLine("※検索対象はカレントディレクトリです。"); Console.WriteLine("※パターンにはワイルドカードが使えます。"); Console.WriteLine("※コピー先ディレクトリが存在しない場合、自動的に作成されます。"); Console.WriteLine(" /m ファイルをコピーではなく移動させます。"); Console.WriteLine(" /r サブディレクトリも再帰的に検索します。"); } } }