Is the directory order returned by Directory.GetDirectories () guaranteed to be ordered?

Although not specified in the documentation , Directory.GetDirectories() always returns a lexicographically sorted array of directory names. Is it safe to rely on this implementation detail (it suits my needs), or should I be paranoid and sort the directory listings as needed?

 [Test] public void SortedDirectories() { string[] directories = Directory.GetDirectories(@"C:\Windows"); Assert.That(directories, Is.Ordered); } 
+4
source share
3 answers

What you see is an NTFS artifact. Other file systems (in particular, FAT or network file systems) may not show the same behavior.

If you need sorting, sort it yourself (perhaps make sure it is already in order, as this is probably a likely scenario).

For example, the following program:

 using System; using System.IO; using System.Collections; public class Foo { public static void Main(string[] args) { string[] subdirectoryEntries = Directory.GetDirectories(@"j:\"); foreach (string d in subdirectoryEntries) { Console.WriteLine( d); } } } 

Displays this output for my FAT formatted JAT disk:

 j:\Qualcomm j:\Precor j:\EditPadPro j:\Qt 

Also, even if NTFS sorts the entries in the directory, it may not sort them the way you want: Old New Thing - why do NTFS and Explorer disagree with sorting the file name?

+6
source

If this is an undocumented implementation detail, then you should not rely on it. Even if this is true now, future versions of the structure are not required to maintain this behavior.

+5
source

No! It works like NTFS.

We have a NAS NAS running Linux, and we are unfortunately chaotic ...

Maybe it is sorted by access date or something, but it does not synchronize with what you see on your local partition or NTFS network share ...

That's why I suggest you be paranoid: D

+3
source

All Articles