Find File Snippet – Depth First And Breadth First Search

Two usefull snippets, if you need to do a quick file search, here a recursive and a breadth first implementation (ignored the not-authorized-exception):
(took me only 2 mins, love .Net 🙂

Depth First Implementation:

static string[] FindFile_DepthFirst(string directoryName, string fileName)
   return Directory.GetFiles(directoryName, fileName, SearchOption.AllDirectories);

Breadth First Implementation:

public string[] FindFile_BreadthFirst(string directoryName, string fileName)
string[] files = new string[0];
ArrayList directories = new ArrayList();
ArrayList foundfiles = new ArrayList();
while (directories.Count > 0)
string n = (string)directories[0];
try{//ignore not-authorized-exception
string[] foundfiles1 = Directory.GetFiles(n, fileName, SearchOption.TopDirectoryOnly);
if (foundfiles1 != null) foundfiles.AddRange(foundfiles1);
try{//ignore not-authorized-exception
string[] subdirectories = Directory.GetDirectories(n);
if (subdirectories != null) directories.AddRange(subdirectories);
return (string[])foundfiles.ToArray(typeof(string));

In my case, i used the breadth first search with a synchronized ArrayList and added found results in this list, as soon as i found them, and with another thread i kept the GUI updated. Here how i created the threadsafe arraylist in case you cant wait for the entire search results 😀 :

ArrayList foundfiles1 = ArrayList.Synchronized(new ArrayList());

Also see – How to Update GUI Control From Non-GUI-Thread Without Marshalling – for updating GUI from a second Thread.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.