I've read discussions about difference between Directory.EnumerateFiles
and Directory.GetFiles
.
I understand that internally they both use
System.IO.FileSystemEnumerableFactory.CreateFileNameIterator()
The difference is that EnumerateFiles
might use deferred execution (lazy), while GetFiles()
does a ToArray
, so the function is already executed.
But what happens if files and folders are added to the dictionary during the iteration. Will the iteration only iterate over the items that were present during the EnumerateFiles()
?
Even worse: what happens if files are removed during iterations: will they still be iterated?
Thanks Michal Komorowski. However when trying his solution myself I saw a remarkable distinction between Directory.EnumerateFiles and Directory.GetFiles():
Directory.CreateDirectory(@"c:\MyTest");
// Create fies: b c e
File.CreateText(@"c:\MyTest\b.txt").Dispose();
File.CreateText(@"c:\MyTest\c.txt").Dispose();
File.CreateText(@"c:\MyTest\e.txt").Dispose();
string[] files = Directory.GetFiles(@"c:\MyTest");
var fileEnumerator = Directory.EnumerateFiles(@"c:\MyTest");
// delete file c; create file a d f
File.Delete(@"c:\MyTest\c.txt");
File.CreateText(@"c:\MyTest\a.txt").Dispose();
File.CreateText(@"c:\MyTest\d.txt").Dispose();
File.CreateText(@"c:\MyTest\f.txt").Dispose();
Console.WriteLine("Result from Directory.GetFiles");
foreach (var file in files) Console.WriteLine(file);
Console.WriteLine("Result from Directory.EnumerateFiles");
foreach (var file in fileEnumerator) Console.WriteLine(file);
This will give different output.
Result from Directory.GetFiles
c:\MyTest\b.txt
c:\MyTest\c.txt
c:\MyTest\e.txt
Result from Directory.EnumerateFiles
c:\MyTest\b.txt
c:\MyTest\d.txt
c:\MyTest\e.txt
c:\MyTest\f.txt
Results:
So the difference in usage between EnumerateFiles and GetFiles is more than just performance.
So if you expect that your folder changes while enumerating carefully choose the desired function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With