1

Hey im trying to create a list of names (with extensions) of all files in the directory, and all files within all, but i need to use a recursive algorithm. Im not sure if im on the right track !!! Quite new to C#

  • 1
    1) Why do you *need* a recursive algorithm? This can be achieved non-recursively. 2) `Recursive` means that your method calls itself in some way. – Corey Feb 28 '13 at 06:44
  • 1
    http://stackoverflow.com/questions/6061957/get-all-files-and-directories-in-specific-path-fast –  Feb 28 '13 at 06:44
  • My software engineering friend said it would be easier using the recursive algorithm – user2118473 Feb 28 '13 at 06:56
  • 1
    How about `FileInfo[] files = pi.GetFiles("*", SearchOption.AllDirectories);`? "Easy" and "recursive" together in one sentence... ^_^ – Corak Feb 28 '13 at 06:57
  • This seems to be a homework. Check out the example here: http://msdn.microsoft.com/library/c1sez4sc.aspx – Feyyaz Feb 28 '13 at 07:01

1 Answers1

4

I usually do this sort of thing with a Queue:

// Make sure rootDir exists first...

var files = new List<string>();
var dirs = new Queue<string>();
dirs.Enqueue(rootDir);

while(dirs.Count > 0 ) {

  var dir = dirs.Dequeue();

  foreach( var fileName in Directory.GetFiles(dir) ) {
    files.Add(fileName);
  }

  foreach( var subDir in Directory.GetDirectories(dir) ) {
    dirs.Enqueue(subDir);
  }
}

// Now populate your list with the files collection.
Andrew Kennan
  • 13,947
  • 3
  • 24
  • 33
  • +1 for not littering the Stack with useless function calls which cannot be inlined ! – Tomer W Feb 28 '13 at 06:50
  • +1 for this pattern. Although I still like recursion more, as I think its easier to follow (shame about the lack of Tail in the C#->CLR compiler). However I prefer to use yield rather than a List. – Aron Feb 28 '13 at 06:59
  • Yeah, my actual code that this is based on is implemented as an iterator block - I'm using it to walk a directory structure of about 1,000,000 xml files... – Andrew Kennan Feb 28 '13 at 07:04
  • 2
    +1. This is educational. Also simply using [SearchOption.AllDirectories](http://msdn.microsoft.com/en-us/library/ms143448.aspx) will achieve the same with less code, including iterator version [Directory.EnumerateFiles](http://msdn.microsoft.com/en-us/library/dd383571.aspx) (4.0+). – Alexei Levenkov Feb 28 '13 at 07:04
  • 1
    Actually thinking a little deeper about this example, I think, assuming I ignore Alexei (great shout by the way). That I would divide the problem into two function. "Recursive get all Directories" and "Enumerate each file in a directory". Switch to using Enumerable GetFile/GetDirectory. Reason being is that you can get the first result faster when using concurrency. – Aron Feb 28 '13 at 07:09