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.
(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):and got the required ordering:
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: