I have a folder that has a number of subfolders that are named as such (2 digit month + 4 digit year) as an example.
102018, 062014, 092018, 042016, 072017, 012016
I need to get a folder list to be able to loop through that is sorted by the year part of the name and then the month part of the name. The name format is always a 2 digit month and a 4 digit year.
The list should then be sorted like
102018, 092018, 072017, 042016, 012016, 062014
I can use the code to get a list
string[] SubDirs = Directory.GetDirectories(@"c:\MainFolder\");
but I don't know how to sort the folder names as I need. Can anyone help?
You can temporarily store the date as yyyyMM and sort on that.
To avoid problems extracting the date, I made sure that the directory name starts with six digits.
using System;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string dirToExamine = @"C:\temp\testDirs";
/* Get the directories which start with six digits */
var re = new Regex("^[0-9]{6}");
var dirs = new DirectoryInfo(dirToExamine).GetDirectories()
.Where(d => re.IsMatch(d.Name))
.ToList();
/* The directory names start MMyyyy but we want them ordered by yyyyMM */
var withDates = dirs.Select(d => new
{
Name = d,
YearMonth = d.Name.Substring(2, 4) + d.Name.Substring(0, 2)
})
.OrderByDescending(f => f.YearMonth, StringComparer.OrdinalIgnoreCase)
.Select(g => g.Name).ToList();
Console.WriteLine(string.Join("\r\n", withDates));
Console.ReadLine();
}
}
}
(It may look like a lot of code, but I formatted it to fit the width of this column.)
I tested it on these directory names (listed with dir /b
):
012016abcd
042016
062014
0720179876
092018
102018 Some text
and got the required ordering:
102018 Some text
092018
0720179876
042016
012016abcd
062014
If you then wanted to do something with the files in each of those directories in that order, it is quite easy because you can use .GetFiles()
on a DirectoryInfo instance:
foreach(var di in withDates)
{
FileInfo[] files = di.GetFiles();
foreach(var fil in files)
{
Console.WriteLine(fil.Name);
}
}