Home >Backend Development >C++ >How Can I Gracefully Handle UnauthorizedAccessException When Using Directory.GetFiles?

How Can I Gracefully Handle UnauthorizedAccessException When Using Directory.GetFiles?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-07 15:11:45578browse

How Can I Gracefully Handle UnauthorizedAccessException When Using Directory.GetFiles?

Robust File Retrieval: Handling UnauthorizedAccessException in Directory.GetFiles

File system operations often encounter permission issues, resulting in UnauthorizedAccessException when using Directory.GetFiles. This exception typically halts the entire process if a single inaccessible directory is encountered. A more robust solution involves individually checking directory access.

This improved approach, detailed below, iterates through each directory, allowing for graceful handling of access restrictions.

Selective File Retrieval Solution

The AddFiles method recursively processes directories. It uses lambda expressions to add file paths to a list, ignoring directories with restricted access.

<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)
    {
        // Ignore access denied errors and continue processing other directories.
    }
}</code>

This revised method efficiently handles UnauthorizedAccessException exceptions within a try-catch block. The program continues execution, collecting files from accessible directories without crashing. This provides better control and prevents premature termination due to access limitations. The use of foreach loops improves readability compared to the original ToList().ForEach() approach.

The above is the detailed content of How Can I Gracefully Handle UnauthorizedAccessException When Using Directory.GetFiles?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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