Reputation: 10824
I've a directory like this with some sub-directories :
root
child-1
child-1-1
child-1-1-1
...
child-1-1-n
child-1-2
child-1-2-1
...
child-1-2-n
...
child-2
child-2-1
child-2-1-1
...
child-2-1-n
child-2-2
child-2-2-1
...
child-2-2-n
child-N
with this code:
var dirInfo = new DirectoryInfo(@"c:\root");
var folders = dirInfo.GetDirectories().ToList();
foreach (var item in folders)
{
Console.WriteLine(item.Name);
}
I just get 1st levels ;
child-1
child-2
child-3
....
child-n
now I wan to get list of root
directory in 2 level :
child-1
child-1-1
child-1-2
child-2
child-2-1
child-2-2
...
I think it is possible with recursive function but I'm not sure about that.
Thanks in advance.
Upvotes: 2
Views: 2742
Reputation: 20140
this should help you, just specify how deep you want to go in the main method
using System;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.BufferHeight = 500;
listDirec(@"c:\program files", 1, 2);
Console.ReadKey();
}
static void listDirec(string path, int start, int end)
{
var dirInfo = new DirectoryInfo(path);
var folders = dirInfo.GetDirectories().ToList();
foreach (var item in folders)
{
Console.WriteLine("".PadLeft(start * 4, ' ') + item.Name);
if (start < end)
listDirec(item.FullName, start + 1, end);
}
}
}
}
Upvotes: 1