Tuesday, February 08, 2005

Breadth-first file enumeration

At last some code...


How to enumerate the filesystem without recursion.


public static void ShowAllFiles(String path)
{
   Queue q = new Queue();
   DirectoryInfo dir = new
      DirectoryInfo(path);
   FileSystemInfo[] entries;

   while(true)
   {
      entries = dir.GetFileSystemInfos("*");

      for (Int32 i = 0
         ; i < entries.Length
         ; i++)
      {
         if (FileAttributes.Directory
            == (entries[i].Attributes
            & FileAttributes.Directory))
         {
            // Process subfolder later.
            q.Enqueue(entries[i]);
            continue;
         }

         // We have a file.
         Debug.WriteLine(
            entries[i].FullName);
      }

      // Are there subfolders?
      if (0 == q.Count) { break; }
      dir = q.Dequeue() as DirectoryInfo;
   }
}


No comments: