Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Directory.GetFiles()

Tags:

.net

.net-2.0

System.IO.Directory.GetFiles() returns a string[]. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date?

Update: MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient.

like image 251
Joel Coehoorn Avatar asked Sep 09 '08 20:09

Joel Coehoorn


1 Answers

If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos(). You can then sort these using one of the extension methods in System.Linq, e.g.:

DirectoryInfo di = new DirectoryInfo("C:\\"); FileSystemInfo[] files = di.GetFileSystemInfos(); var orderedFiles = files.OrderBy(f => f.CreationTime); 

Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though.

like image 76
Ian Nelson Avatar answered Sep 19 '22 21:09

Ian Nelson