Although not mentioned in the documentation, Directory.GetDirectories()
appears to always return a lexicographically-sorted array of directory names. Is it safe to rely on this implementation detail (it is suitable for my needs) or should I be paranoid and sort my directory lists as needed?
[Test]
public void SortedDirectories()
{
string[] directories = Directory.GetDirectories(@"C:\Windows");
Assert.That(directories, Is.Ordered);
}
What you're seeing is an artifact of NTFS. Other file systems (specifically FAT or network filesystems) may not show the same behavior.
If you need the collection to be sorted, sort it yourself (maybe check for it already being in order first, since that's probably a likely scenario).
For example, the following program:
Displays this output for my FAT formatted J: drive:
Also, even though NTFS sorts directory entries, it may not sort them the way you want: Old New Thing - Why do NTFS and Explorer disagree on filename sorting?