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

Hi, I have a lot of files in a folder. These files have a date and time in a file name in a specific format. I need to extract the date from the name and then sort it by date in ascending order. Example file name: -

format_type_2011-07-12-13-00-12.txt

I used to use createTime. But now the requirement is changed.

var Files = new DirectoryInfo(FileDirectory).GetFiles() .OrderBy(f => f.CreationTime) .ToList(); 

How can I do it? Any help is appreciated.

+6
source share
6 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 format information) are already in ISO8601 order (first year, then month, then date, etc.), you can simply sort based on a string without having to convert to date.

+7
source

You can use regular string operators in your orderby order to retrieve the part you want to sort:

  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); } 
+1
source

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 a link to FileInfo if necessary: http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

0
source

You are close:

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

I think this code should work for you:

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

Source: https://habr.com/ru/post/892340/


All Articles