Is the order of directories returned by Directory.GetDirectories() guaranteed to be ordered?
Although not mentione开发者_如何转开发d 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:
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 J: drive:
j:\Qualcomm
j:\Precor
j:\EditPadPro
j:\Qt
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?
If its an undocumented implementation detail then you should not rely on it. Even if it holds true now, future versions of the framework are under no obligation to keep this behaviour.
No! it works like that on NTFS.
We have a NAS network server running Linux and we get unfortunately chaotic behavior...
Maybe it sorts by date accessed or something but it is not in sync with what you would see on your local partition or an NTFS network share...
That is why I suggest you to be paranoid :D
精彩评论