How to get access to system folders when enumerating directories?

断了今生、忘了曾经 提交于 2019-11-29 05:22:52

There is no way in .NET to override privileges of the user you are running this code as.

There's only 1 option really. Make sure only admin runs this code or you run it under admin account. It is advisable that you either put "try catch" block and handle this exception or before you run the code you check that the user is an administrator:

WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
MessageBox.Show(file.FullName);
}
}

try calling this method putting one more try catch block before calling - this will mean top folder lacks required authorisation:

     static void RecursiveGetFiles(string path)
    {
        DirectoryInfo dir = new DirectoryInfo(path);
        try
        {

            foreach (FileInfo file in dir.GetFiles())
            {
                MessageBox.Show(file.FullName);
            }
        }
        catch (UnauthorizedAccessException)
        {

            Console.WriteLine("Access denied to folder: " + path);
        }

        foreach (DirectoryInfo lowerDir in dir.GetDirectories())
        {
            try
            {
                RecursiveGetFiles(lowerDir.FullName);

            }
            catch (UnauthorizedAccessException)
            {

                MessageBox.Show("Access denied to folder: " + path);
            }
        }
    }

}
kaeruthefrog

You can manually search the file tree ignoring system directories.

// Create a stack of the directories to be processed.
Stack<DirectoryInfo> dirstack = new Stack<DirectoryInfo>();
// Add your initial directory to the stack.
dirstack.Push(new DirectoryInfo(@"D:\");

// While there are directories on the stack to be processed...
while (dirstack.Count > 0)
{
    // Set the current directory and remove it from the stack.
    DirectoryInfo current = dirstack.Pop();

    // Get all the directories in the current directory.
    foreach (DirectoryInfo d in current.GetDirectories())
    {
        // Only add a directory to the stack if it is not a system directory.
        if ((d.Attributes & FileAttributes.System) != FileAttributes.System)
        {
            dirstack.Push(d);
        }
    }

    // Get all the files in the current directory.
    foreach (FileInfo f in current.GetFiles())
    {
        // Do whatever you want with the files here.
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!