I am trying to enumerate through files on my computer using the below code but everytime it hits a file or dir that I don’t have permission to read it throws an exception. Is there any way I can continue searching after the exception has been thrown? I know some people have had similar issues but is there any other way of doing this other than checking every file/folder individually?
try
{
string[] files = Directory.GetFiles(@"C:\", "*.*",SearchOption.AllDirectories);
foreach (string file in files)
{
Console.WriteLine(file);
}
}
catch
{
}
Thanks for any help as this is driving me mad!
I came across the same problem just today. I hacked together the following code. If you want to use it in a real product you might need to improve the error handling. Since this was for a one-shot script I didn’t care much.
To use it you can either:
which first enumerates all files, stores all file names in memory and only then displays them. Alternatively you can:
Which writes while enumerating and thus doesn’t need to keep all filenames in memory at the same time.