When you call WriteDirectories recursively, you can pass a variable to each call denoting a (recursion)level . Using this, you can simply put spaces before exiting.
Therefore, you will need to change your code as follows:
static void WriteDirectories(string path, int level = 0) { string[] dirs = Directory.GetDirectories(path); for (int i = 0; i < dirs.Length; i++) { for (int j = 0; j < level; j++) { Console.Write(" "); } Console.WriteLine(dirs[i]); WriteDirectories(dirs[i], (level + 1)); } }
If you need more than one place per level, you can just change the inner loop, j < 2 * level will give you 2 spaces per level, etc.
Update (thanks to David)
Instead of an inner loop, you can use new string(' ', level) to create a new string containing the specified level -times character.
Thus, the internal for -loop will be replaced by Console.Write(new string(' ', level)); .
source share