C:\Documents and Settings' is denied

Blader 156 Reputation points
2020-11-25T18:07:44.527+00:00

Hello.

I used the code below. If i it run "C:\Documents and Settings' is denied" appears. How can I skip denied folders?

Thank You.

  string rootDirectory = System.IO.DriveInfo.GetDrives()[0].RootDirectory.FullName;
    string[] files = System.IO.Directory.GetFiles(rootDirectory,
                "file.exe", System.IO.SearchOption.AllDirectories);

    foreach (var str in files)
    {
        Console.WriteLine(files);
    }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,534 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114K Reputation points
    2020-11-25T19:48:04.55+00:00

    Check if this example finds all accessible files:

    string rootDirectory = System.IO.DriveInfo.GetDrives( )[0].RootDirectory.FullName;
    
    List<string> files = new List<string>( );
    
    void scan( DirectoryInfo di )
    {
        try
        {
            files.AddRange( di.EnumerateFiles( "file.exe" ).Select( f => f.FullName ) );
    
            foreach( var sd in di.EnumerateDirectories( ) )
            {
                scan( sd );
            }
        }
        catch( UnauthorizedAccessException )
        {
            Console.WriteLine( "Skipped: {0}", di.FullName );
        }
    }
    
    scan( new DirectoryInfo( rootDirectory ) );
    

    (If local functions are not available, then move the scan function).

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Blader 156 Reputation points
    2020-11-26T16:06:05.133+00:00

    Thank you, Viorel-1.
    Best regards.

    0 comments No comments