The function to get a directory listing in C# takes one parameter, the directory to start looking in. It will then retrieve a list of files and folders in that directory and for each folder it finds, it will call itself on that folder. Each time the function finds files or folders it will add them to a StringBuilder
object and return the directory listing to the calling function. If that function is itself, then the new directory listing is appended to the existing listing. This process repeats until all files and folders have been listed. The function then returns the completed recursive directory listing in C# back to the originating method, in the example shown, the main function.
Simple Directory Listing in C#
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StringBuilder dirList = directoryListing("C:Inetpub", "");
Console.WriteLine(dirList.ToString());
}
static StringBuilder directoryListing(string path, string indent)
{
StringBuilder result = new StringBuilder();
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] rgDirs = di.GetDirectories();
foreach (DirectoryInfo dir in rgDirs)
{
result.AppendLine(indent + dir.Name);
result.Append(directoryListing(path, indent + "..").ToString());
}
return result;
}
}
}
If you want, you could adapt this directory listing in C# to return a List