I found something similar here but have been unable to get it working. I'm very new to LINQ and so not entirely sure what's going on with it. Any help would be appreciated. I have directory names like:
directory-1
article-about-something-else
I want to sort these by name but have been unable thus far. They are on a network drive residing on a RedHat server. The directory listing comes in a garbled mess in a seemingly random order.
Here's some of what I've tried:
DirectoryInfo dirInfo = new DirectoryInfo("Z:\\2013");
var dirs = dirInfo.GetDirectories().OrderBy(d => dirInfo.Name);
foreach (DirectoryInfo dir in dirs)
{
string month = dir.Name;
Console.WriteLine(dir.Name);
var monthDirInfo = new DirectoryInfo("Z:\\2013\\" + month);
var monthDirs = monthDirInfo.GetDirectories().OrderBy(d => monthDirInfo.CreationTime);
foreach (DirectoryInfo monthDir in monthDirs)
{
string article = monthDir.Name;
Console.WriteLine(monthDir.Name);
sb.AppendLine("<li><a href=\"/2013/" + month + "/" + article + "\">" + TextMethods.GetTitleByUrl("2013/" + month + "/" + article) + "</a></li>");
}
}
Any help would be greatly appreciated. I'm sort of at a loss at the moment. I'm sure I'm missing something obvious, too.
You are ordering by the name of your root folder instead of the name of each sub-directory.
So change...
var dirs = dirInfo.GetDirectories().OrderBy(d => dirInfo.Name);
to ...
var dirs = dirInfo.EnumerateDirectories().OrderBy(d => d.Name);
and
var monthDirs = monthDirInfo.GetDirectories()
.OrderBy(d => monthDirInfo.CreationTime);
to ...
var monthDirs = monthDirInfo.EnumerateDirectories()
.OrderBy(d => d.CreationTime);
I have used EnumerateDirectories
because it is more efficient. GetDirectories
would collect all directories first before it would begin ordering them.
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