There is a recursive function for indexing directories and files. I need to create a hierarchical view of the file structure. I iterate over the variable (let it be i) on each pass of the recursive function. That is, deep into the iteration goes as it should. But when it comes to the next folder, which is higher level, the iteration does not roll back to the previous state. How can you avoid this phenomenon? An example of how it should be done: 1-2-3-4-5-6-2-3-4-2-3 (numbers are node identifiers). what turns out: 1-2-3-4-5-6-7-8-9-9-10-11

And, yes, YaP-C #.

  • will the code be? - petya
  • in my opinion, this is where the problem is in the implementation logic, and not in the code. In any elementary recursive function, if we set a counter variable, this phenomenon will be observed. - Vasily Koshelev

1 answer 1

private static void Inspect(string dir, int level) { Console.WriteLine("{0}\t{1}", level, dir); foreach (var file in Directory.EnumerateFiles(dir)) { Console.WriteLine("{0}\t{1}", level, file); } foreach (var directory in Directory.EnumerateDirectories(dir)) { Inspect(directory, level + 1); } } 


  • level variable will increase continuously. That is, if you return to the folder one level higher (when there are no more directories), the iteration will not return to the previous level. But this is the ideal. you will just keep track of the sequence number of the folder in the parent folder. - Vasily Koshelev
  • Yeah. Not bad. Now, I will try again to implement. - Vasily Koshelev
  • @Tyler, attention, conditional code: int i = 0; iter (i); iter (int i) {if (i <3) iter (i + 1); print i; } Output: 3210. That is, calling iter (i + i) does not change the value of the variable i in the called function. - user6550