
This is a snippet I use to retrieve all the sub-directories of a given directory. It returns the values in a single HashTable so remember the first entry is the initial root directory
Instructions: Pass the method the directory, it will get the root directory, then drill down getting all subs of the directory provided
//namespace reference
using System;
using System.IO;
/// <summary>
/// method for finding all the sub-directories for a given directory
/// </summary>
/// <param name="dir">directory to retrieve info for</param>
/// <returns></returns>
public Hashtable ListAllSubDirectories(string dir)
{
//variable to hold our results
Hashtable dirResults = new Hashtable();
try
{
//get the root directory of the directory path provided
Directory.GetDirectoryRoot(dir);
//get the last location of a backslash ("\")
int loc = dir.LastIndexOf('\\');
//remove the last backslash
dir = dir.Remove(loc, dir.Length - loc);
//add the root to the HashTable
dirResults.Add("Root Directory", dir);
//create a string array to hold all the directories under the root
string[] directories = Directory.GetDirectories(dir);
foreach (string directory in directories)
{
dirResults.Add("SubDirectory:",directory);
}
}
catch (Exception ex)
{
dirResults = null;
MessageBox.Show(ex.Message);
}
return dirResults;
}-Offline- |