Resolve Directory.GetFiles
thrown UnauthorizedAccessException
Exception
When using Directory.GetFiles
to obtain a file path, you may encounter a UnauthorizedAccessException
exception if the program lacks access rights to a specific folder in the specified directory. This exception occurs after the method has attempted to access an inaccessible folder, causing the operation to terminate prematurely.
To solve this problem, it is recommended to use an iterative approach rather than trying to access the entire directory tree at once. The following code example demonstrates how to safely probe a directory and collect files:
<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) { // 以优雅的方式处理访问被拒绝的异常。 // 可以记录问题或继续处理下一个目录。 // 例如:Console.WriteLine($"Access denied to directory: {path}, Exception: {ex.Message}"); } }</code>
By probing directories one by one, you can avoid terminating the entire operation if access to a specific folder is denied. This allows the program to continue processing files in the directory to which it has access rights. This method handles the results of Directory.GetFiles
more clearly than the original example, avoids unnecessary ToList()
and ForEach()
calls, and improves code efficiency and readability.
The above is the detailed content of How to Handle `UnauthorizedAccessException` Errors When Using `Directory.GetFiles`?. For more information, please follow other related articles on the PHP Chinese website!