Fast, Heuristic Disk Search

Warning! Some information on this page is older than 3 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Jan 2012

Fast, Heuristic Disk Search

In March 2007 I've written an algorithm which I called "Fast, heuristic disk search" and published it in my article Szybkie, heurystyczne przeszukiwanie dysku (in Polish) on Today I went back to it, improved it a bit and I think it is a good opportunity to present it once again, this time in English :)

The problem is about searching hard disk, looking for a file or directory with particular name. Naive approach, which is used by file searching functions in programs like Total Commander, uses depth-first search, so it enters C:\, then C:\Program Files, then C:\Program Files\Adobe etc., spending lots of time in places where it probably won't find the file we are looking for.

Game developers know that searching algorithm can be significantly improved by using some heuristics that will drive algorithm towards (probably) right direction. We do it in A* pathfinding. Does a similar principle could be used also when searching for a file?

My particular problem was configuring a program with path to a console tool, let's say fxc.exe shader compiler from DirectX SDK. We could present a textbox where user has to enter path to this tool. We could also make "Browse" button with an open file dialog to simplify locating it. But wouldn't be great if program tried to locate it automatically on first run? Some installed programs store path in a registry key, but if it doesn't, we have no idea where could it be if we don't look for it among files and directories on hard disk.

My algorithm tries to locate given file or directory in given time limit by searching all given directories and their subdirectories. The improvement I propose here is inteligent management of the order in which we process these directories.

The algorithm uses two collections: a queue of directories to process and a set of already visisted directories. Here is the code in C#:

/* Intelligent search for a file or directory by name, on the hard disk.
 * Can throw exceptions on some errors, while silently ignore other.
 * targetName - name of the target like "fxc.exe" or path suffix like @"bin\x86\fxc.exe".
 * interestingDirNames - case-insensitive strings with parts of
 *     directory names that make these directories particularly
 *     interesting, while not very common.
 *     Example: { "microsoft", "dx", "directx", "sdk" }
 * startDirs - paths to directories to start search from. For example,
 *     path to Program Files or hard disk root directories.
 * Returns path to found target or null if not found in given time.
public static string IntelligentSearch(
  string targetName, bool targetIsDirectory,
  string[] interestingDirNames, string[] startDirs, TimeSpan timeout)
  DateTime endTime = DateTime.Now + timeout;

  // Paths to process
  LinkedList<string> PathQueue = new LinkedList<string>();
  // Path already processed in form Key=Path, Value="1"
  System.Collections.Specialized.StringDictionary Processed =
    new System.Collections.Specialized.StringDictionary();

  foreach (string startDir in startDirs)

  // Processing loop - berform breadth first search (BFS) algorithm
  while (PathQueue.Count > 0)
    // Get directory to process
    string Dir = PathQueue.First.Value;
    // Already processed
    if (Processed.ContainsKey(Dir))
    // Add to processed
    Processed.Add(Dir, "1");

      string targetPath = Path.Combine(Dir, targetName);
      if (targetIsDirectory)
        if (Directory.Exists(targetPath))
          return targetPath;
        if (File.Exists(targetPath))
          return targetPath;

      foreach (string SubDir in Directory.GetDirectories(Dir))
        bool dirIsInteresting = false;
        if (interestingDirNames != null && interestingDirNames.Length > 0)
          string subDirName = Path.GetFileName(SubDir);
          foreach (string interestingName in interestingDirNames)
            if (subDirName.IndexOf(interestingName, StringComparison.InvariantCultureIgnoreCase) != -1)
              dirIsInteresting = true;

        if (dirIsInteresting)
    catch (Exception) { }

    if (DateTime.Now > endTime)
      return null;

  return null;

Example usage, which finds my fxc.exe in a fraction of a second:

string[] interestingDirNames = {
  "x86" };

List<string> startDirs = new List<string>();


foreach (System.IO.DriveInfo Drive in System.IO.DriveInfo.GetDrives())
  if (Drive.DriveType == System.IO.DriveType.Fixed)

string result = Globals.IntelligentSearch(

Comments (1) | Tags: algorithms .net | Author: Adam Sawicki | Share


2015-04-10 09:23:43
chanel bags,
flat iron,
converse shoes,
ferragamo outlet,
gucci belt,
hollister kids,
insanity workout calendar,
jimmy choo shoes,
air jordan shoes,
juicy couture,
juicy couture outlet,
kate spade,
louis vuitton outlet,
michael kors outlet online,
michael kors,
michael kors purses,
michael kors,
michael kors outlet online sale,
north face jackets,
oakley outlet,
pandora charms,
prada outlet,
prada shoes for men,
ray ban sunglasses outlet,
rolex watches,
swarovski outlet,
the north face outlet,
tiffany jewelry,
tiffany co,
true religion jeans outlet,
true religion outlet,
ugg boots,
uggs outlet,
ugg australia,
ugg boots clearance,
cheap oakley,
oakley vault,
ralph lauren outlet online,
ralph lauren outlet,,
toms shoes,
toms outlet,
christian louboutin shoes,
tory burch handbags,
gucci belt,
longchamp bags,,
hermes birkin bag,
cheap nfl jerseys,
beats headphones,
beats by dr dre,
hair straightener,
ray ban sunglasses,
michael kors bags,
michael kors uk,
louis vuitton outlet,
ralph lauren outlet,
nike running,
omega watches,
dresses for weddings,
pandora sale,
thomas sabo,
christian louboutin,
air huarache,
roshe run,
north face uk,
louis vuitton canada,
jordan shoes,
air jordan,
air jordan retro,
nike outlet,
cheap nike shoes,
nike sneakers,
air max 2015,
nike air max 2014,
nike air max 2015,
nike free,
nike running shoes,
supra shoes,
new balance,
mont blanc,
salvatore ferragamo outlet,
mcm bags,
nike mercurial,
celine bags,
roshe runs,
roshe run,
vans shoes,
timberland outlet,
iphone 4s cases,
softball bats,
babyliss pro,
louis vuitton handbags,
burberry outlet,
christian louboutin shoes,
louis vuitton outlet stores,
prada outlet,
michael kors outlet online sale,
michael kors handbags,
tommy hilfiger polos,
mcm handbags,
moncler outlet,
kate spade sale,
barbour quilted jacket,
salvatore ferragamo shoes,
canada goose outlet,
louis vuitton outlet online,
burberry outlet,
hollister clothes,
north face outlet online,
barbour jackets,
north face jackets outlet,
north face jackets women,
polo ralph lauren outlet online,
ralph lauren outlet,
ralph lauren outlet online,
beats by dre outlet,
louis vuitton outlet online,
gucci outlet,
longchamp outlet,
moncler clearance,
ralph lauren shirts,
hermes handbags,
beats by dre outlet,
coach factory outlet online,,,
michael kors outlet,,
oakley vault,
hermes bags,
marc jacobs bags sale,
nike air max,
woolrich clearance,
coach outlet store,
coach bags outlet,
coach handbags outlet,
gucci sale,
coach outlet online,
michael kors outlet store,
gucci handbags,
the north face outlet,
ugg boots clearance,
tommy hilfiger coupons,
uggs outlet,
louis vuitton outlet,
calvin kleins outlet,
christian louboutin,
jordan retro,
burberry outlet,
abercrombie fitch,

Post comment

Nick *
Your name or nickname
Your contact information (optional, will not be shown)
Text *
Content of your comment
Calculate *
(* - required field)
STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2016 Adam Sawicki
Copyright © 2004-2016 Adam Sawicki