Elegantly handle the UnauthorizedAccessException exception that occurs when Directory.GetFiles traverses the directory
When performing file and directory operations, you may encounter Directory.GetFiles
exceptions when using the UnauthorizedAccessException
method. This exception occurs when a method attempts to access a directory for which the user lacks appropriate permissions.
To solve this problem, it is recommended to probe directories one by one instead of traversing the entire directory tree. This approach allows finer control over operations. The following code demonstrates an improved approach:
<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>
In this method, UnauthorizedAccessException
is captured and handled gracefully, allowing the program to continue execution and possibly discover other accessible files. The iteration continues through the directory hierarchy, calling itself recursively to explore subdirectories.
By using this technique, you can avoid Directory.GetFiles
method termination due to access denied errors and maintain control of the directory traversal process. This method uses a foreach
loop instead of ToList().ForEach()
, making it more readable and efficient.
The above is the detailed content of How Can I Handle UnauthorizedAccessException When Using Directory.GetFiles to Traverse Directories?. For more information, please follow other related articles on the PHP Chinese website!