0

I need to add files that were created a month ago in list. Like this:

if (f.CreationTime.Date < DateTime.Now) 
    fileNames.Add(f.Name);

But i don't undertand how to check this condition correctly.

Rafalon
  • 4,450
  • 2
  • 16
  • 30

3 Answers3

2

I suggest using Linq: let's filter out all the required files' names and then add them with a help of AddRange

  // Date to compare with
  DateTime compareDate = DateTime.Now.AddMonths(-1);

  fileNames.AddRange(new DirectoryInfo(@"c:\MyFiles") //TODO: put the right path
    .EnumerateFiles() //TODO: Provide a filter (say, "*.txt") if required
    .Where(file => file.CreationTime < compareDate)
    .Select(file => file.Name));

If fileNames has nothing to preserve you create it:

  DateTime compareDate = DateTime.Now.AddMonths(-1);

  List<string> fileNames = new DirectoryInfo(@"c:\MyFiles") //TODO: put the right path
    .EnumerateFiles() //TODO: Provide a filter (say, "*.txt") if required
    .Where(file => file.CreationTime < compareDate)
    .Select(file => file.Name)
    .ToList(); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Try this:

if (f.CreationTime.Date < DateTime.Now.AddMonths(-1))
{
   fileNames.Add(f.Name);
}
Hubii
  • 348
  • 1
  • 14
0

You can check for the last Creation date using File.GetCreationDate()

    DateTime filedate = File.GetCreationTime(@"sample.txt");
    int res = DateTime.Compare(filedate,DateTime.Now.AddMonths(-1));
    if(res == -1 || res == 0)
    {
       //do your task
    }
Lucifer
  • 1,594
  • 2
  • 18
  • 32
  • There's a `)` missing at the end of your second line of code, right before `;` – Rafalon May 15 '18 at 10:14
  • 3
    @Lucifer Microsoft has also implemented the [operators](https://msdn.microsoft.com/en-us/library/system.datetime.op_lessthan(v=vs.90).aspx) '<' and '>'. So you use these to compare two dates, no point in using DateTime.Compare – Alexandre Beaudet May 15 '18 at 10:16
  • thanks rafalon added it – Lucifer May 15 '18 at 10:16
  • @alexandreBEaudet see lin's comment in this{https://stackoverflow.com/a/3059628/6947385} answer – Lucifer May 15 '18 at 10:21
  • 1
    Since he didn't add his code or anything, can't really take his comment for a sure thing. Been using, as probably most of the other c# dev, the operator and never failed me – Alexandre Beaudet May 15 '18 at 11:14
  • 1
    why to increase time complexity - by comparing dates ( `res = DateTime.Compare(d1,d2)`) and then check for comparison result ( `if(res == 1)` ) when you can direct compare (`if (d1 > d2)` \) dates ? – Amit May 15 '18 at 11:41