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

How to Handle UnauthorizedAccessException When Using Directory.GetFiles()?

Patricia Arquette
Release: 2025-01-07 15:02:40
Original
560 people have browsed it

How to Handle UnauthorizedAccessException When Using Directory.GetFiles()?

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

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!

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