# Fastest way searching specific files

I got thousands of files with a specific file extension in thousands of sub folders. Now, what is the fastest way to search with a pattern? I tried the method DirectoryInfo.GetFiles(rootfolder) (~8 minutes) and a recursive custom method (~5 minutes).

 private void WalkDirectoryTree(DirectoryInfo dr, string searchname)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
try
{
files = dr.GetFiles(searchname + ".*");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

if (files != null)
{
foreach (FileInfo fi in files)
{
}
subDirs = dr.GetDirectories();

foreach (DirectoryInfo di in subDirs)
{
WalkDirectoryTree(di, searchname);
}
}
}


Is there any faster way to do it?

• What type is allFiles ? Do you need FileInfo or the filename ? Dec 19 '14 at 11:43
• It's a List<FileInfo>. I need the FileInfo, not only the filename. Dec 19 '14 at 11:46
• An how do you use the List<> ? Do you just iterate over the entries and process them in some way? Dec 19 '14 at 11:47
• Yes that's it. It's not really relevant I think. Dec 19 '14 at 11:48
• yes it is relevant Dec 19 '14 at 11:49

foreach (DirectoryInfo di in subDirs)
{
WalkDirectoryTree(di, searchname);
}


Do

Parallel.ForEach(subDirs, dir => WalkDirectoryTree(dir, searchname));


Notice that by doing this allFiles will be accessed concurrently so change your collection to a ConcurrentBag.

• @greenhoorn I would be glad to hear the improvements you had after the replacement. Dec 19 '14 at 13:45
• I will share it as soon as I test it. Could take 2 weeks :-) Dec 19 '14 at 14:22
• Thanks for your answer! It still takes 2 minutes but that's significantly faster than before. I would say 2 minutes for millions of files is acceptable :-) Jan 9 '15 at 9:41

You can just use DirectoryInfo.EnumerateFiles() method which returns an IEnumerable<FileInfo> and therefor if you access them by the enumerator they will be evaluated when they are accessed.

private void WalkDirectoryTree(DirectoryInfo dr, string searchname)
{
foreach (FileInfo file in FindFiles(dr, searchname + ".*"))
{
// process file