How to get files from a directory based on a condition

I'm looking to get specific files from a directory based on their creation date. I want ".jpeg" files to have their creation dates more than 30 days before they are extracted. how are we going? I wrote the code but I am stuck in the Where section

FileInfo[] fi;
DirectoryInfo di= new DirectoryInfo(@"C:\src_folder");

fi = di.GetFiles("*.jpeg").Where(....

      

Now here in the "Where" section, I'm not sure how I proceed to get files that have been around for more than 30 days.

+3


source to share


4 answers


I think this might be helpful:



FileInfo[] fi;
DirectoryInfo di= new DirectoryInfo(@"C:\src_folder");

DateTime beginning = DateTime.UtcNow.AddDays(-30);
fi = di.GetFiles("*.jpeg")
       .Where(file => file.CreationTimeUtc < beginning)
       .ToArray();

      

+3


source


GetFiles

returns an array FileInfo

. Each item will have a property CreationTimeUtc

that you can use to filter only items older than 30 days:

var limit = DateTime.UtcNow.AddDays(-30);
fi = di.GetFiles("*.jpeg").Where(f => f.CreationTimeUtc < limit).ToList();

      



You want a file that was modified 30 days ago to be used LastWriteTimeUtc

instead of CreationTimeUtc

.

+2


source


try this:

DateTime from_dt = DateTime.Now.AddDays(-30);
DateTime to_dt = DateTime.Now;

var dir = new DirectoryInfo(@"C:\src_folder");

var files = dir.GetFiles("*.jpeg")
  .Where(file=>file.LastWriteTime >= from_dt && file.LastWriteTime <= to_dt);

      

+1


source


I don't know if I got your question, do you need files that were created above 30 days ago? If yes:

   fi = di.GetFiles("*.jpeg").Where(file => file.CreationTimeUtc < DateTime.UtcNow.AddDays(-30)).ToArray();

      

+1


source







All Articles