Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I would like to get only the top-directories (not any recursive) within a given directory in the sort-order of the last modified file date descending. The quest here is, that the order must be exactly like windows explorer does, even if some directories have the same file date.

This code I have tried where Path1 can be any work folder:

C#
Directory.GetDirectories(Path1, "*", SearchOption.TopDirectoryOnly).OrderByDescending(d => new DirectoryInfo(d).LastWriteTime).ToArray();


It like works and not works. Sometimes it retrieves the expected sort order, sometimes it doesn't. If many directories have identical file dates the order becomes distorted which means it doesn't equal any longer to the Windows Explorer sort order exactly. Some files are moved up or moved down or in the middle.
If I do the same with an old API-Code of VB6 I get the exact sort order every time, it doesn't matter even if the file dates are equal or not - the explorer file order is preserved in my VB6 application in any directory which I retrieve.
C# seems to do something different or the above one-liner needs to be adjusted to be more accurate. I have no idea on this, API I would not like to use for such trivial task.

What I have tried:

I tried also to sort by "DirectoryInfo(d).LastWriteTimeUtc" but it made no difference. I have checked for other codes, but they all use LINQ and are somewhat identical with my code. I don't mind to use LINQ, but I need the exact directory sort order like in Windows Explorer (nothing with the same file date shall be moved up or down in the listing!). Maybe the toArray() distorts the order, but I would need it as an array. So far I cannot find the reason.
Posted
Updated 17-Mar-16 6:40am

1 solution

Can't you use DirectoryInfo object?

Like this:

C#
{
	Comparison<FileSystemInfo> dirComp = (x, y) =>
	{
		int i = y.LastAccessTime.CompareTo(x.LastAccessTime);
		if (i == 0) {
			i = string.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase);
		}
		return i;
	};

OR

	DirectoryInfo info = new DirectoryInfo("Path1");

	var  topFolders = info.EnumerateDirectories().OrderByDescending(d => (d.LastAccessTime)).ThenBy(d => (d.Name)).Select(d => (d.FullName)).ToArray();
;
}
 
Share this answer
 
v2
Comments
Jens Madsen, Højby 17-Mar-16 13:53pm    
Var topFolders = info.EnumerateDirectories().OrderByDescending(d => (d.LastAccessTime)).ThenBy(d => (d.Name)).Select(d => (d.FullName));

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900