C#•Recurses, Foldered Again

Listing 1. The BuildTree method loops through a folder structure recursively using the Directory.GetDirectories method. Use this method to list the files in each folder. Search each folder recursively to locate all the nested folders and files.

// Recursively loops through folder structure and 
// loads all folders and files into TreeView. 
// Each iteration gets files and folders 
// immediately within current folder.
private void BuildTree(string sPath, 
   TreeNodeCollection oNodes)
{
   // Load all folders in current path into array
   string[] aFolders = 
      Directory.GetDirectories(sPath);
   // Loop through all folders in current path, 
   // create nodes for them and load them into 
   // TreeView
   foreach(string sTempFolder in aFolders)
   {
      // Strip path out and retrieve folder name 
      // only
      string sFolder = 
         sTempFolder.Substring(sPath.Length);
      // Create node for folder and add it to 
      // TreeView
      oNodes.Add(CreateFolderNode(sFolder));
   }
   // Load all JPGs in current path into array
   string[] aFiles = Directory.GetFiles(sPath, 
      "*.jpg");
   // Loop through files in current path, create 
   // nodes for them and load them into TreeView
   foreach(string sFile in aFiles)
   {
      // Create node for file; add it to 
      // TreeView. Pass in path with file name of
      // file (text for file node)
      oNodes.Add(CreateFileNode(sFile, 
         sFile.Substring(sPath.Length)));
   }         
   // Recursively call GetFolders method for 
   // subfolder
   for(int i = 0; i < oNodes.Count; i++)
   {
      // If the node is a folder ...
      if (oNodes[i].Type == "folder")
      {
      // Recursively call GetFolders method for 
      // subfolder
         BuildTree(aFolders[i] + "\\", 
            oNodes[i].Nodes);
      }
   }            
}