As everyone else pointed out, the best means is via the DirectoryInfo.GetDirectories(string searchPattern, SearchOption searchOption) method. But make sure to a) manually perform the recursion in order to avoid an UnauthorizedAccessException, and b)in the case of ROM drives, check if IsReady to avoid a "Device is not ready" error.
Now, to provide an example or finding a given directory name on a specific drive, or on all available logical drives (excluding network drives), please see the following:
static void Main(string[] args)
{
DirectoryInfo selectedDir;
selectedDir = FindDirectory("Exported");
if (selectedDir == null)
{
Console.WriteLine("No directory was found matching the provided name.");
}
else
{
Console.WriteLine("The folloiwng directory path was selected:");
Console.WriteLine(selectedDir.FullName);
}
Console.ReadLine();
}
static DirectoryInfo FindDirectory(string dirNameToFind, DriveInfo driveToSearch = null)
{
if ((String.IsNullOrEmpty(dirNameToFind)) || (!IsValidDirectoryName(dirNameToFind))) { return null; }
List<directoryinfo> possibleDirs = new List<directoryinfo>();
if (driveToSearch == null)
{
foreach (DriveInfo availableDrive in DriveInfo.GetDrives())
{
if ((availableDrive.DriveType != DriveType.Network) && (availableDrive.IsReady))
{
DirectoryInfo driveRootDir = new DirectoryInfo(availableDrive.Name);
GetDirectories(possibleDirs, driveRootDir, dirNameToFind);
}
}
}
else
{
DirectoryInfo driveRootDir = new DirectoryInfo(driveToSearch.Name);
GetDirectories(possibleDirs, driveRootDir, dirNameToFind);
}
if (possibleDirs.Count() == 0) { return null; }
if (possibleDirs.Count() ==1) { return possibleDirs[0]; }
Console.WriteLine("Multiple directories were found matching the provided name.");
Console.WriteLine("Please indicate which directory to use.");
Console.WriteLine();
for (int i = 1; i <= possibleDirs.Count(); i++) { Console.WriteLine(i.ToString() + ": " + possibleDirs[i - 1].FullName); }
Console.WriteLine();
bool vaidInput = false;
int selectedItemNo = -1;
do
{
Console.WriteLine("Enter corrisponding number and press enter.");
string userInput = Console.ReadLine();
if (String.IsNullOrEmpty(userInput)) { continue; }
vaidInput = int.TryParse(userInput, out selectedItemNo);
}
while ((!vaidInput) && (Enumerable.Range(1, possibleDirs.Count()).Contains(selectedItemNo)));
return possibleDirs[selectedItemNo - 1];
}
static bool IsValidDirectoryName(string directoryName)
{
foreach (char c in Path.GetInvalidPathChars())
{
if (directoryName.Contains(c)) { return false; }
}
return true;
}
static void GetDirectories(List<directoryinfo> dirList, DirectoryInfo rootDir, string dirNameToFind = null)
{
try
{
foreach (DirectoryInfo subDir in rootDir.GetDirectories("*", SearchOption.TopDirectoryOnly))
{
if ((String.IsNullOrEmpty(dirNameToFind)) || (subDir.Name == dirNameToFind)) { dirList.Add(subDir); }
GetDirectories(dirList, subDir, dirNameToFind);
}
}
catch (UnauthorizedAccessException) { }
}