0

I need to get a list of files and folders in a subdirectory.
The file list all clear, but what about a list of directories not sure

using System;
using System.IO;

namespace ConsoleApplication15
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo dir = new DirectoryInfo(@"D:\Temp");
            Console.WriteLine("============ list of directories =============");
            foreach (var item in dir.GetDirectories())
            {
                Console.WriteLine(item.Name);
                Console.WriteLine("== list of subdirectories ==");
                foreach (var it in item.GetDirectories())
                    Console.WriteLine(it.Name);
                Console.WriteLine();
            }
            Console.WriteLine("============== list of files ==============");
            foreach (var item in dir.GetFiles())
            {
                Console.WriteLine(item.Name);
            }
            Console.ReadLine();
        }
    }
}

There is a better way?

Example of directories:

folder1   
- folder2   
-- folder3   
-- folder4   
--- folder5   
Amazing User
  • 3,473
  • 10
  • 36
  • 75

1 Answers1

2

As @Mitch Wheat suggested, there is the option SearchOption.AllDirectories. However, be aware that this may result in an UnauthorizedAccessException when it hits folders which it cannot access.

So the best solution for me always was to use a recursive function which can ignore inaccessible folders.

For a recursive solution, see Ignore folders/files when Directory.GetFiles() is denied access here on StackOverflow or Folder recursion

Community
  • 1
  • 1
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222