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.
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.
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();
Try this:
if (f.CreationTime.Date < DateTime.Now.AddMonths(-1))
{
fileNames.Add(f.Name);
}
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
}