Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort files by date in file name using c#?

Tags:

c#

linq

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.

like image 941
User13839404 Avatar asked Jul 08 '11 15:07

User13839404


People also ask

How do I sort files in a folder?

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.

How do I sort files in Uipath?

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.


2 Answers

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.

like image 108
BrokenGlass Avatar answered Sep 20 '22 02:09

BrokenGlass


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);
    }
like image 33
Eric J. Avatar answered Sep 20 '22 02:09

Eric J.