You are using the right tool for the right job. If you have a small number of files, you probably want to just use Directory.GetFiles() and load them into memory.
Directory.EnumerateFiles() , on the other hand, when you need to save memory by listing files one at a time.
This is similar to the argument about whether to do everything lazy or just use it when necessary. I think it helps put things in perspective, because everything lazy without a good reason is an excess.
You have a trade-off between simplicity and efficiency . It is clear that an enumerator that does not actually contain files, but gives them one at a time, is more complex than a string array. The ability to store this counter in IEnumerable<string> is a wonderful abstraction, but the point remains.
It can also be harder to predict performance. With GetFiles() you know that the execution cost arises when the method is called. EnumerateFiles() does nothing until it is listed.
Intention is important. If you use EnumerateFiles() in a directory that, as you know, will not have so many files, then you simply use it blindly without understanding. The computer is also working on issues. If I run something on a server with 24 GB of RAM, then I can more likely use memory puzzles like GetFiles() than if I were on a server with 1 GB of RAM.
If you have no idea how many files there will be or will not be aware of the environment in which the code will work, then it would be wise to make a mistake with caution and use a memory-efficient version.
There are many variables to consider, and a good programmer takes these things into account and does things purposefully.
source share