The reason is because of the way they're used. DirectoryInfo::EnumerateFiles
works on the current directory, so by its nature, the effort of getting the directory loaded into the object is already done - the worrying about path too long etc. is done by the construction of the DirectoryInfo
object, eg:
DirectoryInfo di = new DirectoryInfo(...); // Gets the directory - many things could go wrong here
di.EnumerateFiles(); // Since we have a DirectoryInfo object, we already know the directory is ok - we've checked for the other problems already.
Directory.EnumerateFiles
is a static method, which means it doesn't work on an existing object that's already been successfully created. Therefore it has to load the directory (which could cause any number of exceptions), and THEN enumerate the files.
It's essentially the top two steps combined into one.
Another way of looking at it, in English, would be:
- Load this directory into an object for me c:\myfolder
DirectoryInfo myObject = new DirectoryInfo(@"C:\myfolder");
If it's not valid eg. because the path is too long, you'll get an exception here.
If it works, it's now loaded information about the directory into the object. So you can say
- Hey, that directory I loaded - enumerate the files on it for me.
myObject.EnumerateFiles();
Since it's loaded the folder already, it doesn't need to do it again because it knows it's working and completely fine. The only possibilities are not found (if between these two lines, you delete the folder on your computer) and a SecurityException which is that you don't have permission to enumerate.
The other example combines those two steps, and says "Enumerate all the files in this folder for me"
So it will load the folder (which could generate all those exceptions) and then enumerate the files, all in a single step.
Some information about PathTooLongException:
The maximum length you can have for a file including the full path is 260 characters. Therefore if you have a folder like c:\aaaaaaaaaaaaaaaaa..... that is 250 characters long, you might think by putting a file that is 20 characters long into the folder (for a total of 270) would cause the DirectoryInfo to throw an exception.
However it's simply not possible to put a file in the folder - windows gives the error:
The file name(s) would be too long for the destination folder.
So it's not possible for DirectoryInfo.EnumerateFiles to be tricked into exceeding the maximum length of 260 because it's impossible to create anything more than 260 characters long.