-1

如何使用 C# 遍历具有指定嵌套索引的目录?

小例子:

Folder1
|__Folder1.1
|  |__Folder1.1.1
|__Folder1.2

Folder2
|__Folder2.1
   |__Folder2.1.1
   |__Folder2.1.2
      |__Folder2.1.2.1

使用最大嵌套索引 1,我们将获得以下目录:(
嵌套级别 0) Folder1、Folder2
(嵌套级别 1)  Folder1.1、Folder1.2、Folder2.1

提前致谢!

4

1 回答 1

0

Directory.GetDirectories您可以使用该函数编写递归方法:

class Program
{
    static void Main()
    {
        Loop(@"c:\work", 1);
    }

    static void Loop(string root, int nestingIndex = 0)
    {
        if (nestingIndex < 0)
        {
            return;
        }
        foreach (var folder in Directory.GetDirectories(root))
        {
            Console.WriteLine(folder);
            Loop(folder, nestingIndex - 1);
        }
    }
}
于 2012-04-07T19:06:01.787 回答