简体   繁体   中英

Ignore folder C# (System.UnauthorizedAccessException)

A quick question. I'm executing this code:

listBox1.Items.AddRange( Directory.GetDirectories("C:\\Users\\", "*" ,SearchOption.AllDirectories));

It list all directories and subdirectories in C:\\Users\\ (yes I know, it maybe blow up my pc)

Anyways, I am getting this error (System.UnauthorizedAccessException)

This error comes from the special folders "C:\\Users\\All Users\\" and "C:\\Users\\USER\\AppData\\"

How can I ignore this folders to program keeping listing all dir and subd without Exceptions?

Unfortunately it's not possible to filter out all directories without the required permissions. You need to implement your own recursive function to deal with the problem by catching the UnauthorizedAccessException . Since there could be many exceptions the way is not very fast but reliable like explained in this question :

[...] permissions (even file existence) are volatile — they can change at any time [...]

Here is my possible solution:

public static void GetDirectories(string path, Action<string> foundDirectory)
{
    string[] dirs;
    try
    {
        dirs = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
    }
    catch (UnauthorizedAccessException)
    {
        //Ignore a directory if an unauthorized access occured
        return;
    }

    foreach (string dir in dirs)
    {
        foundDirectory(dir);
        //Recursive call to get all subdirectories
        GetDirectories(dir, foundDirectory);
    }
}

Simply call the function like

List<string> allDirectories = new List<string>();
GetDirectories(@"C:\Users\", d => allDirectories.Add(d));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM