Overcoming Unauthorized Access Exception in Directory.GetFiles
When using Directory.GetFiles() to recursively search for files within a directory tree, it's possible to encounter an UnauthorizedAccessException when the program attempts to access a folder without sufficient permissions. This exception aborts the operation prematurely.
To work around this issue, it's recommended to adopt a more controlled approach by probing each directory individually. The code below demonstrates this technique:
private static void AddFiles(string path, IList<string> files) { try { Directory.GetFiles(path) .ToList() .ForEach(file => files.Add(file)); Directory.GetDirectories(path) .ToList() .ForEach(dir => AddFiles(dir, files)); } catch (UnauthorizedAccessException ex) { // Handle inaccessible directory (e.g., move on to the next one) } }
In this approach, AddFiles() iterates through all files and subdirectories within path. When it encounters a directory that cannot be accessed, it simply skips it and continues with the remaining directories. By doing so, the program can continue its file search without abruptly terminating due to an authorization issue.
The above is the detailed content of How to Handle UnauthorizedAccessException When Using Directory.GetFiles()?. For more information, please follow other related articles on the PHP Chinese website!