简体   繁体   中英

Why am I getting an access denied error for the Documents and Settings folder?

I'm writing a program that gets all directories and sub-directories. I'm using the following code:

DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
    string[] directories = Directory.GetDirectories(drive.Name, "*", SearchOption.AllDirectories);
}

But I'm getting an exception stating "Access to the path 'C:\\Documents and Settings\\' is denied."

I'm using Windows 7 and I don't see a C:\\Documents and Settings\\ folder in Explorer. I enabled "Show hidden files and folders" and even try to type in the path directly but it gives the following error: "C:\\Documents and Settings is not accessible. Access denied."

Why is Directory.GetDirectories() pulling a directory that doesn't seem to exist?

This directory is what is known as a junction point , which should be pointing to c:\\users.

From the MSDN documentation:

These junction points can be identified as follows:

They have the FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_HIDDEN, and FILE_ATTRIBUTE_SYSTEM file attributes set.

They also have their access control lists (ACLs) set to deny read access to everyone.

Applications that call out a specific path can traverse these junction points if they have the required permissions. However, attempts to enumerate the contents of the junction points will result in failures.

After looking for an answer for some time - I decided to write the code on my own.

I'm sharing here the basic idea and not the full code - Take the important part and use it implement it in your code.

Worked for me.

public void directoryCrawl(string startFolder)
    {

    try
    {
        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);

        /* here you can add "dir" to some kind of list of your choice. */

        foreach (System.IO.DirectoryInfo directory in dir.GetDirectories())
        {
            try
            {
                directoryCrawl(directory.FullName);
            }
            catch
            {
                Console.Writeline("Access denied to: \"" + directory.FullName + "\".");
            }
        }
    }
    catch
    {
        if (!String.IsNullOrEmpty(startFolder))
        {
            Console.Writeline("Access denied to: \"" + startFolder + "\".");
        }
        }
        return;
    }

I don't know how to work around, but I can tell you that WinXP used that path. Old programs written with an expectation of being able to access that folder would not have been Win7 compatible so Microsoft redirects it to your Users folder.

If I do Start -> Run c:\\Documents and Settings I also get the Access is Denied error. So something is there.

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