Exception caused by Directory.GetFiles method due to access restrictions
When accessing a network file system or a file system in a controlled environment, you may encounter restricted access to certain folders. This causes methods such as Directory.GetFiles to throw exceptions, interrupting program execution.
Problem Analysis
When the Directory.GetFiles method encounters an inaccessible directory, it will throw an UnauthorizedAccessException exception. Unfortunately, before catching this exception, the method has failed and cannot recover.
Solution: Detect directories one by one
To solve this problem, it is recommended to probe one directory at a time instead of recursively searching the entire directory tree. This way, you can catch and handle exceptions on a per-directory basis, avoiding premature program termination.
Example implementation
The following is an example method that iterates through a directory tree and adds file paths to a list, excluding files from access-denied directories:
<code class="language-csharp">private static void AddFiles(string path, IList<string> files) { try { foreach (string file in Directory.GetFiles(path)) { files.Add(file); } foreach (string subdirectory in Directory.GetDirectories(path)) { AddFiles(subdirectory, files); } } catch (UnauthorizedAccessException ex) { // 忽略无法访问的目录,继续处理其他目录 } }</code>
This method ensures that the program continues execution even if it encounters a directory that it does not have access to, allowing you to process files in a directory that does have access. This improved version avoids the use of ToList().ForEach()
and uses a clearer and more readable foreach
loop, improving the maintainability of the code.
The above is the detailed content of How Can I Handle UnauthorizedAccessException When Using Directory.GetFiles?. For more information, please follow other related articles on the PHP Chinese website!