3

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?

4

1 回答 1

3

您当前的Where表达式将在昨天或之前的这个时间为您提供所有文件。也许你想要类似的东西:

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

这将检查文件最后修改日期的日期部分是否与指定输入日期的日期部分匹配。

于 2013-05-25T22:13:52.280 回答