How to get access to system folders when enumerating directories?

前端 未结 3 852
野趣味
野趣味 2020-12-17 08:00

I am using this code:

DirectoryInfo dir = new DirectoryInfo(\"D:\\\\\");
foreach (FileInfo file in dir.GetFiles(\"*.*\",SearchOption.AllDirectories))
{
    M         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 08:46

    You can manually search the file tree ignoring system directories.

    // Create a stack of the directories to be processed.
    Stack dirstack = new Stack();
    // 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.
        }
    }
    

提交回复
热议问题