Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all files in a directory skipping unauthorized files?

Tags:

c#

I need to get a list of all files in my C drive which allow writing and reading, so I tried like this:

string[] files = Directory.GetFiles(@"C:\\", "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
    Console.WriteLine(file);
}

But I instantly get UnauthorizedAccess Exception

like image 772
Ilkay Solotov Avatar asked Jan 02 '21 17:01

Ilkay Solotov


1 Answers

If you are using .NET Core 2.1 or later, you should be able to use Directory.GetFiles(String, String, EnumerationOptions) and pass EnumerationOptions.IgnoreInaccessible:

Gets or sets a value that indicates whether to skip files or directories when access is denied (for example, UnauthorizedAccessException or SecurityException).

var files = Directory.GetFiles(@"C:\\", "*.*", 
    new EnumerationOptions { 
        IgnoreInaccessible = true, 
        RecurseSubdirectories = true,
});

Notes:

  • Since you are searching recursively, you might also consider switching to Directory.EnumerateFiles(String, String, EnumerationOptions) for performance:

    The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

  • In your title you wrote, How can I get all files in a directory skipping unauthorized files? but in your question you wrote, I need to get a list of all files in my C drive which allow writing and reading.

    Just because a file is returned by Directory.GetFiles() with IgnoreInaccessible = true, that does not mean you can conclude the file is actually writable and readable. To do that, you need to look at the effective permissions of the file. See Checking for directory and file write permissions in .NET. Or you could just try opening the file and checking the CanRead and CanWrite properties of the stream, see C# file status (readable, writeable, is file, is directory) by Zbigniew for details.

like image 105
dbc Avatar answered Nov 14 '22 21:11

dbc