Website development and design blog, tutorials and inspiration

Simple Directory Listing in C#

Recursive directory listing in C#

By , Written on in C#

Simple Directory Listing in C#

271 words, estimated reading time 2 minutes.

This little C# code snippet will produce a recursive directory listing in C# and get a list of all the files and folders in the directory, returning them as a formatted StringBuilder object.

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#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. StringBuilder dirList = directoryListing("C:\Inetpub", "");
  13. Console.WriteLine(dirList.ToString());
  14. }
  15.  
  16. static StringBuilder directoryListing(string path, string indent)
  17. {
  18. StringBuilder result = new StringBuilder();
  19. DirectoryInfo di = new DirectoryInfo(path);
  20. DirectoryInfo[] rgDirs = di.GetDirectories();
  21.  
  22. foreach (DirectoryInfo dir in rgDirs)
  23. {
  24. result.AppendLine(indent + dir.Name);
  25. result.Append(directoryListing(path, indent + "..").ToString());
  26. }
  27. return result;
  28. }
  29. }
  30. }

If you want, you could adapt this directory listing in C# to return a List with the full path of the file if you need to access or process files, or you could use this method to recursively search for a file or folder. Why not let me know what you come up with in the comments section - and share your code to help others looking for similar tasks!

Last updated on: Tuesday 20th June 2017

Comments

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.