I’m a bit confused here. I wrote the following script to add files of a certain extension type to a List and it DOES work, just not for the root of C: Here’s the code first…
// Create an empty list
List<string> scanFiles = new List<string>();
// Split possible extention list into array
string[] scanExtensions = @"exe,com".Split(',');
try
{
foreach (string extension in scanExtensions)
{
// Add collection for this filetype to the list of files
scanFiles.AddRange(Directory.GetFiles("C:\\", "*." + extension, SearchOption.AllDirectories));
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
// Display results
foreach(string sf in scanFiles)
{
Console.WriteLine(sf);
}
So if I run the above code, I get an error – but not the error I expect. It displays the following…
ERROR: Access to the path ‘C:\Documents and Settings\’ is denied.
I’d understand this if I hadn’t specified ‘C:\’ as the directory path! If I change this to any valid directory (such as C:\Program Files), the code works fine. Can anyone explain this?
Thanks,
Simon
SearchOption.AllDirectoriesmeans your code will drill down into (forbidden) territory.Better be prepared to handle this kind of error. For a solution without catching exceptions you’ll need
DirectoryInfo.GetFiles()to get FileInfo objects instead of strings and verify your access rights ahead of time.But you will still need to handle exceptions (File/Dir not found) because of concurrency so you might as well forget about the
FileInfos.