-1

I am starting with C# programming. I would like to ask you for help. I have a list of files from one directory. I would like to sort these files by date of creation/modification.

part of code:

List<string> _f = new List<string>();
string[] _files = Directory.GetFiles(_p);
foreach (string _fi in _files){_f.Add(_fi);};
_f.Sort((x, y) => DateTime.Compare(x.Created, y.Created))

Problem is that ".Created" does not exist. I was not able to find any relevant parameter which can be used to sort by DateTime. Could you help me please? Thank you in advance.

cotablise
  • 65
  • 6

1 Answers1

3

You can try FileInfo class

   var _files = Directory
     .EnumerateFiles(_p)
     .Select(file => new FileInfo(file))
     .OrderBy(info => info.LastWriteTime) 
     .Select(info => info.FullName)
     .ToArray(); // If you want to get files' names as an array 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Perfect. Thank you very much. I added following code to my program: foreach (string it in _files){Console.WriteLine(it);}. Problem is that files are sorted by name and not by creationtime. Sorry if it is trivial, but I am newcomer. – cotablise Nov 12 '17 at 19:25
  • @cotablise: Please, check what file's time you actually want: `CreateTime` (creation) or `LastWriteTime` (last modification) – Dmitry Bychenko Nov 12 '17 at 19:35
  • yeah, you are right. Thank you very much for your help. – cotablise Nov 12 '17 at 19:44
  • Note: the last projection (`.ToArray()`) is either exactly what you need, not quite what you need (`.ToList()` perhaps) or _not needed at all_. – Tom Blodget Nov 12 '17 at 20:15
  • Thank you for additional info. – cotablise Nov 13 '17 at 15:23