Search code examples
c#windowswinformsfile-handlingdirectory-structure

How can I get directories of a folder and then its directories' directory and so on...?


I am coding in C#, if you can't provide the code but you might be able explain how to achieve the result please do answer.

I want to have the names(path) of all of the folders and files located in a directory and then have their sub directories and files and so on until there are none left.

In simple words I want to map the whole directory.

I want an output similar to the tree command in command prompt but only paths: ├── dirPath (level 0) │ └── f1 (level 1) │ │ └──f0 (level 2) │ │ │ └──file.txt (level 3) │ │ │ └──f4 (level 3) │ │ └──f3 (level 2) │ └── f2 (level 1)

Code that I have used but doesn't return what I want:

foreach (string dir in Directory.GetDirectories(dirPath)) {
      Console.WriteLine(dir);
}

Output (only returns level 1)

dir/f1
dir/f2

Also tried this code:

foreach (string dir in Directory.GetDirectories(dirPath)) {
      foreach(string subdir in Directory.GetDirectories(dir)) {
            Console.WriteLine(subdir);
      }
      Console.WriteLine(dir);
}

Output (returns level 1 and 2)

dir/f1/f0
dir/f1/f3
dir/f1
dir/f2

What I want

dir/f1/f0/file.txt
dir/f1/f0/f4
dir/f1/f3
dir/f1
dir/f2

Is there anyway of achieving this? The "getting files" part is not a problem if we can get the directory paths, we can use foreach loop for files.

Thank you.


Solution

  • string path = @"C:\YourPath";
    string[] folders = Directory.GetDirectories(path, "*", SearchOption.AllDirectories);
    string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
    List<string> filesAndFolders = folders.Union(files).ToList();
    filesAndFolders.Sort();