-1

如何使用 c# 获取硬盘上的所有目录(带有子目录)?

响应示例:

C:\
C:\1
C:\2
C:\2\1
C:\2\1\4
C:\2\1\4\5
C:\2\1\4\5\6
C:\3
4

2 回答 2

3
using System.IO;

var directories = new List<string>(Directory.GetDirectories(@"c:\", "*", SearchOption.AllDirectories));

directories.ForEach(directory => Console.WriteLine(directory));
于 2015-12-16T22:19:58.557 回答
0

贾斯汀的回答会 100% 奏效。如果这更多是关于学习技术而不是获得结果,那么您将需要一个递归函数。这意味着我们需要一个函数来调用它返回的结果。

public static void GetDirectories(string path, bool recursive)
{
    Console.WriteLine(path); // write the name of the current directory
    if (recursive) // if we want to get subdirectories
    { 
        try // getting directories will throw an error if it is a path you don't have access to
        {
            foreach (var child in Directory.GetDirectories(path)) // get all the subdirectories for the given path
            {
                GetDirectories(child, recursive); // call our function for each sub directory
            }
        }
        catch (UnauthorizedAccessException ex) // handle unauthorized access errors
        {
            Console.WriteLine(string.Format("You don't have permission to view subdirectories of {0}",path));
        }

    }
}

然后调用它:

static void Main(string[] args)
{
    GetDirectories("c:\\", true);
    Console.ReadLine();
}

同样,如果您只是想按照贾斯汀的答案列出清单,但这就是您自己可以做到的方式。

于 2015-12-17T00:28:34.003 回答