C# C GetFiles.Where(日期范围)

C# C GetFiles.Where(日期范围),c#,C#,我正在尝试显示上周创建的Excel文件,从周一到周五。例如,如果是周一,我想查找上周一到周五之间的文件。如果是同一周的星期五,我想查询相同的时间范围 我知道下面的代码将给我昨天的结果,但是我如何获得日期范围?谢谢 string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls") .Where(file => new FileInfo(file).CreationTime.Date == DateTime.Today.AddD

我正在尝试显示上周创建的Excel文件,从周一到周五。例如,如果是周一,我想查找上周一到周五之间的文件。如果是同一周的星期五,我想查询相同的时间范围

我知道下面的代码将给我昨天的结果,但是我如何获得日期范围?谢谢

string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls")
   .Where(file => new FileInfo(file).CreationTime.Date == DateTime.Today.AddDays(-1))
   .ToArray();
诸如此类:

string[]files=Directory.GetFilesFBD.SelectedPath,*.xls
.Wherefile=>new FileInfofile.CreationTime.Date>=DateTime.Today.AddDays-2&&new FileInfofile.CreationTime.Date首先需要检查DateTime.Now.Day以获取一周中的某一天,然后添加或减去x个天数来创建范围,并在范围中添加and子句。其中:

  //Add AND clause to .where and add or subtract days occordingly to create range, instead of using == you would use <= end and >= start
    string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls")
       .Where(file => new FileInfo(file).CreationTime.Date >= DateTime.Today.AddDays(-1) && new FileInfo(file).CreatTime.Date <= DateTime.Today.AddDays(1)
       .ToArray();
DateTime不仅可与==比较,还可与。我会用更便宜的:

使用StartOfWeek方法

检查它是否必须如果您将小时考虑在内,因为DateTime.Today将为您提供12:00:00am,因此如果该字段有小时,则如果您将And子句添加到您的中,则将不起作用。如下面的示例答案所示,..Date>=minDate&.Date可能重复DateTime.Today.AddDays-1直到AddDays1是OP想要的范围。如果今天是星期一,他想选择上周,在所有其他情况下,他想从星期一到星期五选择本周。@TimSchmelter我举了一个例子,说明了如何创建范围,我在回答上面的注释中解释了,在上面的注释中,他需要获取DateTime.Now.Day来获取一周的当前日期,然后从DateTime.Today中加上和减去x,以创建正确的范围。
DateTime lastMonday = DateTime.Today.StartOfWeek(DayOfWeek.Monday);
if(lastMonday == DateTime.Today)
   lastMonday = lastMonday.AddDays(-7);
DateTime lastFriday = lastMonday.AddDays(4);
string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls")
    .Select(f => new { File = f, CreationDate = File.GetCreationTime(f).Date })
    .Where(x => x.CreationDate >= lastMonday && x.CreationDate <= lastFriday)
    .Select(x => x.File)
    .ToArray();
var fileInfos = Directory.GetFiles(FBD.SelectedPath, "*.xls").Select(file => new FileInfo(file));

var files = fileInfos
                .Where(fi => fi.CreationTime.Date >= DateTime.Today.AddDays((int)DayOfWeek.Monday - (int)DateTime.Today.DayOfWeek - 7) 
                       && 
                       fi.CreationTime.Date < DateTime.Today.AddDays((int)DayOfWeek.Saturday - (int)DateTime.Today.DayOfWeek) - 7)
                .ToArray();