NathanRO
Как и все остальные заметили, лучший способ это через запись directoryinfo.GetDirectories(строковый параметр searchpattern, searchoption указывает, нужно searchoption указывает, нужно) метод. Но обязательно а)вручную выполните рекурсию, чтобы избежать неавторизованного исключения Accessexception, и Б) в случае дисков ROM проверьте, готово ли устройство, чтобы избежать ошибки "устройство не готово".
Теперь, чтобы привести пример или найти заданное имя каталога на определенном диске или на всех доступных логических дисках (исключая сетевые диски), пожалуйста, смотрите следующее:
static void Main(string[] args)
{
DirectoryInfo selectedDir;
// Find a directory called "Exported" on any available logical drive.
// If you need to find the directory on a spicific logical drive, provide the DriveInfo for the drive to search.
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)
{
// Prevent null strings or searching for invalid directory names (contains invalid charaters).
if ((String.IsNullOrEmpty(dirNameToFind)) || (!IsValidDirectoryName(dirNameToFind))) { return null; }
List<directoryinfo> possibleDirs = new List<directoryinfo>();
if (driveToSearch == null)
{
// No drive was specified, so search all drives.
foreach (DriveInfo availableDrive in DriveInfo.GetDrives())
{
// Only check non-network drives and drives with removable media that are ready (disk installed).
if ((availableDrive.DriveType != DriveType.Network) && (availableDrive.IsReady))
{
DirectoryInfo driveRootDir = new DirectoryInfo(availableDrive.Name);
GetDirectories(possibleDirs, driveRootDir, dirNameToFind);
}
}
}
else
{
// A drive was provided, so only search that drive.
DirectoryInfo driveRootDir = new DirectoryInfo(driveToSearch.Name);
GetDirectories(possibleDirs, driveRootDir, dirNameToFind);
}
if (possibleDirs.Count() == 0) { return null; } // No dir matches, so return null.
if (possibleDirs.Count() ==1) { return possibleDirs[0]; } // Only one dir matched, so return that dir.
// More than one directory exsits matching the provided name. So ask the user to which directory they want.
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; } // Handle blank entries.
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)
{
// Perform manual recurrsion to prevent "UnauthorizedAccessException" errors.
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) { } // Do nothing.
}