-1

My task is to print out every subdirectory without using a recursion. I have to use two functions, one will fill the array with every subdirectory and then print this array, the other is for resizing the array. I know this is a bad practice that I have to resize array every time I want to add something to it, but it is how I should do it. Also, I'm not allowed to use the function of getting the parent of a directory and SearchOption.AllDirectories. It has to be done using loops.

class Program {

    static void Main(string[] args) {
        string path = @"D:\Heaven Benchmark 4.0";
        WriteDirectories(path);
        Console.ReadKey();
    }

    static void WriteDirectories(string path) {
        string[] dirs = Directory.GetDirectories(path);
        string[] allDirs = new string[0];

        for (int i = 0; i < allDirs.Length; i++) {
            Console.WriteLine(allDirs[i]); 
        }
    }

    static void ResizeArray(ref string[] arr, int newSize) {
        string[] newArr = new string[newSize];
        for (int i = 0; i < newSize - 1; i++) {
            newArr[i] = arr[i];
        }
        arr = newArr;
    }
}

I'm thinking about filling array allDirs with every existing subdirectory of a path and then printing it out. is there any better and easier way of doing this?

Crionics
  • 19
  • 5

2 Answers2

3

assuming you have read access to all subdirectories:

replace

string[] dirs = Directory.GetDirectories(path);

with

string[] dirs = Directory.GetDirectories(path, "*", SearchOption.AllDirectories);
fubo
  • 44,811
  • 17
  • 103
  • 137
  • i forgot to mention that i'm not allowed to use that either. it just has to be done using loops – Crionics Jun 19 '18 at 12:57
  • printing out every subdirectory without using recursion and printing out every subdirectory by using loops are different requirements/questions – fubo Jun 19 '18 at 13:01
0

If something is very intuitive to you using recursions, then just go and implement that. It's quite easy to transform a recursion based algorithm to a iterative version as explained by this SO post.

Following the top answer of the post you will find yourself implementing something like this:

static void WriteDirectories(string path)
{
    string[] dirs = Directory.GetDirectories(path);
    var allDirs = new List<string>();
    Stack<string> stack = new Stack<string>(dirs);
    while (stack.Any())
    {
        var dir = stack.Pop();
        allDirs.Add(dir);
        foreach (var tmp in Directory.GetDirectories(dir))
        {
            stack.Push(tmp);
        }
    }
    // Do something with allDirs
}
Freggar
  • 1,049
  • 1
  • 11
  • 24