I'm trying to use this code to get all directories on a drive. It works good until it gets an access violation. A lot of people have said to use try-catch to get around the exceptions, but the way I'm trying to do it I only get the directories up til the exception. I must be missing something obvious, but don't see how it can jump over the errors. I tried this as EnumerateDirectories and GetDirectories, but couldn't see an obvious difference.
I tried pasting this as code in Firefox but couldn't. Worked fine in Chrome.
private void button1_Click(object sender, EventArgs e)
{
try
{
string dirPath = @"C:\Data\";
// LINQ query.
var dirs = from dir in Directory.EnumerateDirectories(dirPath, "*", SearchOption.AllDirectories) select dir;
// Show results.
foreach (var dir in dirs)
{
MessageBox.Show(dir);
}
Console.WriteLine("{0} directories found.", dirs.Count<string>().ToString());
// Optionally create a List collection.
List<string> workDirs = new List<string>(dirs);
}
catch (UnauthorizedAccessException UAEx)
{
MessageBox.Show(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
MessageBox.Show(PathEx.Message);
}
}