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);
}
GetDirectories(String, String) Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory. public: static cli::array <System::String ^> ^ GetDirectories(System::String ^ path, System::String ^ searchPattern);
If the directory specified by path has no subdirectories, or if no directories match searchpattern, an empty array is returned. The following code displays all subdirectories of c:\ whose names start with the letter P:
The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. The Sort()method is the standard Array.Sort(), which takes in IComparables (among other overloads), so if you sort by creation date, it will handle localization based on the machine settings. Share Improve this answer
If the specified directory has no subdirectories, or no subdirectories match the searchPatternparameter, this method returns an empty array. Only the top directory is searched. If you want to search the subdirectories as well, use the GetDirectories(String, String, SearchOption)method and specify AllDirectoriesin the searchOptionparameter.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With