Hi I have many files in a folder. Those files have date and time in the file name in specific format. I need to extract the date from the name and then sort it by date in ascending order. File Name example :-
format_type_2011-07-12-13-00-12.txt
Earlier I was using by createTime. But now requirement is changed.
var Files = new DirectoryInfo(FileDirectory).GetFiles()
.OrderBy(f => f.CreationTime)
.ToList();
How do i do it? Any help is appreciated.
You can reveal more options from File Explorer's View tab. In the Current view section, click or tap on Sort by. Same as before, the sorting options displayed are specific to that folder's view template. To add more criteria to the Sort by menus, click or tap Choose columns.
OrderByDescending – It is sort files in Descending order. CreationTime – It will sort files based on the creation time of each file in a folder. OrderByAscending – It will sort the files in Ascending order. If you want to get each file in that folder after sorting files then we need to use for each.
This should work:
var di = new DirectoryInfo(FileDirectory);
var Files = di.GetFiles()
.OrderBy( f => f.Name.Substring(f.Name.LastIndexOf('_')+1)
.ToList();
Since your file names (minus the format info) are already in ISO8601 order (year first, then month, then date, etc.) you can just sort based on the string w/o having to convert to a date.
You can use ordinary string operators in your orderby statement to exract the part you want to sort on:
string f1 = "Foo_2011-07-12-13-00-12.txt";
string f2 = "Bar_2011-07-12-13-00-15.txt";
string f3 = "Blah_2011-07-12-13-00-11.txt";
int sortRelevant = "0000-00-00-00-00-00.txt".Length;
List<string> files = new List<string>() { f1, f2, f3 };
var sorted = (from f in files orderby f.Substring(f.Length - sortRelevant) select f);
foreach (string fs in sorted)
{
Console.WriteLine(fs);
}
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