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