JaggenSWE
JaggenSWE

Reputation: 2106

Getting a list of all files with a certain date of last modified

I'm creating a program in c# that will get hold of all the files in a given directory that were created on a specific date and then zip these files and store them in another directory. Sounds plain and simple, I have a license for Teleriks components so that takes care of the zipping business.

BUT in order to select the files I use the following code:

        //Get all files created yesterday
        DateTime to_date = DateTime.Now.AddDays(-1);

        var directory = new DirectoryInfo(@"C:\Path_Of_Files");

        var files = directory.GetFiles()
                    .Where(file => file.CreationTime <= to_date);

        if (files.Count() > 0)
        {
          //Zipping code here
        }

This however gives me ALL the files in the directory, so instead of zipping 700 files, it zips all 53'000 files in the folder, which isn't what I wanted.

When I look in the Windows Explorer I see the correct date in the "Last Modified" column, but for some reason my code refuse to acknowledge the same date. I've tried with both:

        var files = directory.GetFiles()
                    .Where(file => file.CreationTime <= to_date);

and

        var files = directory.GetFiles()
                    .Where(file => file.LastWriteTime <= to_date);

Both with the same result.

What am I doing wrong?

Upvotes: 3

Views: 9876

Answers (1)

Ant P
Ant P

Reputation: 25221

Your current Where expression will give you all files at or before this time yesterday. Perhaps you want something like:

var files = directory.GetFiles()
    .Where(file => file.LastWriteTime.Date == to_date.Date);

This checks that the date portion of the file's last modified date matches the date portion of the specified input date.

Upvotes: 3

Related Questions