Directory.EnumerateFiles read order Directory.EnumerateFiles read order arrays arrays

Directory.EnumerateFiles read order


The underlying Win32 API used by .NET is FindFirstFile and FindNextFile. The documentation specifically states:

The order in which this function returns the file names is dependent on the file system type. With the NTFS file system and CDFS file systems, the names are usually returned in alphabetical order. With FAT file systems, the names are usually returned in the order the files were written to the disk, which may or may not be in alphabetical order. However, as stated previously, these behaviors are not guaranteed.

So no, you cannot guarantee the order the files are returned. The other answers provide sufficient ways to work around this behavior.


As far as I can tell, it's not documented - therefore even if you can spot a pattern, you shouldn't rely on it. It may depend on the version of .NET, or the version of the operating system, or simply change between service packs. Instead, if you need some specific order, you should sort it yourself. Of course that unfortunately requires finding all the file names before processing them, but it will give you consistency.

To be honest though, it sounds like you've got a very fragile data model. You haven't really told us enough about what you're doing to fix it, but using the integer index of a file within the results of Directory.EnumerateFiles is surely not the best approach.

If you used the file name instead of the index, that would allow you to process files as you read them, potentially - but there may well be even better approaches, depending on what you're trying to do. Using the name should still be reasonably cheap - it'll just be a single string reference instead of an integer, and even if it's used in multiple places, it'll be several references to the same string object.


The documentation does not specify the order, but you can always force the order you want by employing LINQ's OrderBy function.

You can skip index changes by clearing out references to null, rather than actually removing the items from the array. The tradeoff here is that you must now check if the item at the given index is null.

If you have a more readable data structure in mind that is based on a Dictionary, consider switching to it, and ignore the efficiency concerns until your profiler tells you that you must optimize this particular part of your code.