简体   繁体   中英

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

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.

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);
    }

I think LastWriteTime is what you are looking for. Here is the MSDN link: http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.lastwritetime.aspx

also the link to FileInfo if needed: http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

You are close:

var Files = new DirectoryInfo(@"C:\").GetFiles()
                                     .OrderBy(f => f.LastWriteTime)
                                     .ToArray(); //or .ToList() whatever suits you best

I think that this code should work for you:

var Files = new DirectoryInfo(@"W:\").GetFiles().OrderBy(f=> f.LastWriteTime).ToList();
var Files = new DirectoryInfo(FileDirectory)
                   .GetFiles()
                   .OrderBy(f => f.Name.Substring(f.Name.Length - 23, 19)
                   .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM