You use the right tool for the right job. If you have a small number of files, then you probably want to just use Directory.GetFiles()
and load them into memory.
Directory.EnumerateFiles()
on the other hand is when you need to conserve memory by enumerating the files one at a time.
This is similar to the argument of whether to make everything lazy, or just use it when appropriate. I think this helps put things into perspective because making everything lazy for no good reason is overkill.
You have the trade off of simplicity vs efficiency. Conceptually, an enumerator which doesn't actually contain the files, but yields them one at a time is more complex than a string array. Being able to store that enumerator in an IEnumerable<string>
is a wonderful abstraction, but the point remains.
It may also be more difficult to predict performance. With GetFiles()
you know the performance cost is incurred when the method is called. EnumerateFiles()
does not do anything until it is enumerated.
Intention is important. If you are using EnumerateFiles()
on a directory that you know won't have that many files, then you're just using it blindly without understanding. The computer the code runs on matters, too. If I am running something on a server with 24 GB of RAM then I may be more likely to use memory-hungry methods like GetFiles()
than if I was on a server with 1 GB of RAM.
If you have no idea how many files there will be or unsure what kind of environment the code will run on, then it would be wise to err on the side of caution and use the memory-efficient version.
There are many variables to consider and a good programmer takes these things into consideration and does things purposefully.
GetFiles
is there for backward-compatibility. It was in the original 1.0 .NET framework.EnumerateFiles
was introduced much later - 4.0 or 4.5 if I recall correctly. – GenaroGetFiles
was introduced in 2.0 andEnumerateFiles
in 4.0. – Vanvanadate