Search File recursively in CSharp
Description
The following code shows how to search File recursively.
Example
//from w ww . ja v a 2 s . c o m
using System;
using System.IO;
public class FileSearch {
public static void Main() {
String searchName = "win";
DirectoryInfo myDir = new DirectoryInfo(@"c:\Program Files");
SearchDirectories(myDir, searchName);
}
public static void SearchDirectories(DirectoryInfo dir, String target) {
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files) {
if (file.Name.IndexOf(target) > -1) {
Console.WriteLine(file.Name);
}
}
DirectoryInfo[] dirs = dir.GetDirectories();
foreach (DirectoryInfo subDir in dirs) {
SearchDirectories(subDir, target);
}
}
}