I would like my code to skip or dismiss folders that give errors for whatever reasons. Currently, this code scans properly through folders but stops if any folder gives an error at it. Mostly hidden folders.
I have found these nearly identical questions but these answers only point to different directions not implementing the solution I need and I seem unable to implement any of the solutions into my code. Ive been banging my head for 3 days.
ignore "Unauthorized Access" " function Directory.GetDirectories()"
How to exclude folders when using Directory.GetDirectories
Ignore folders/files when Directory.GetFiles() is denied access
My code is:
//encrypts target directory
public void encryptDirectory(string location, string password)
{
//extensions to be encrypt
var validExtensions = new[]
{
".txt", ".doc"
};
string[] files = Directory.GetFiles(location);
string[] childDirectories = Directory.GetDirectories(location);
for (int i = 0; i < files.Length; i++){
string extension = Path.GetExtension(files[i]);
if (validExtensions.Contains(extension))
{
EncryptFile(files[i],password);
}
}
for (int i = 0; i < childDirectories.Length; i++){
encryptDirectory(childDirectories[i],password);
}
}
The closest answer I think might work is in the question: ignore "Unauthorized Access" " function Directory.GetDirectories()"
gives this code applied to files:
private static string[] GetFilesSafe(string location) {
try {
return Directory.GetFiles(location);
} catch (UnauthorizedAccessException ex) {
Console.Error.WriteLine(ex.Message);
return new string[0];
}
}
Could someone please help me understand what I need in order to implement this type of solution or another within my code, applied to the folders? I know this is not the most efficient way to learn, but is time sensitive. Thanks for your/any help.