Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.EnumerateFiles read order

What is the default read order for the Directory.EnumerateFiles method? Is it consistent?

In my experience so far it seems to be by the date the files were created but I haven't been able to find confirmation of this.

Reason I ask is because part of a program I am working on loads binary files from directories into objects which are in turn loaded into arrays. These objects reference each other by arrays of indices, meaning the order they are loaded into their arrays needs to remain consistent (to avoid shifting indices).

While I'm here, I have another minor question. When files are deleted, it obviously changes the indices of the files loaded into arrays no matter what I do. Any suggestions for avoiding this problem? I've avoided using a dictionary up until now due to worries about storage (would rather not be storing arrays of textual keys if I can avoid it) but if it's the only feasible approach, I may have to implement it anyway.


EDIT: After the excellent tips from your answers, I've refactored to a dictionary approach using the names of the files. The performance impact has been fairly negligible and the readability and maintainability are both vastly improved so it's worked out quite well.

like image 624
Djentleman Avatar asked Dec 31 '12 03:12

Djentleman


1 Answers

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.

like image 158
vcsjones Avatar answered Oct 01 '22 17:10

vcsjones