Home > Backend Development > C++ > How to Handle `UnauthorizedAccessException` Errors When Using `Directory.GetFiles`?

How to Handle `UnauthorizedAccessException` Errors When Using `Directory.GetFiles`?

Mary-Kate Olsen
Release: 2025-01-07 15:21:44
Original
874 people have browsed it

How to Handle `UnauthorizedAccessException` Errors When Using `Directory.GetFiles`?

Resolve Directory.GetFilesthrown UnauthorizedAccessExceptionException

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template