I am trying to find a function to use with the DirectoryInfo().GetFiles
function to only count weekdays when I am looking for files in a date range.
The only function I found is
.Count(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
which is incompatible with fileInfos.Where
DateTime d1 = DateTime.Now;
d2 = d1.AddDays(FileAgeYounger);
DateTime d3 = DateTime.Now;
d4 = d3.AddDays(FileAgeOlder);
if (subfolders == true &
FileExtension != null &
Fileprefix != null &
FileUseRelativeAgeOlder == true &
FileUseRelativeAgeYounger == false & CountWeekDays == true)
{
FileInfo[] fileInfos = new DirectoryInfo(FolderLocation).GetFiles("*.*", SearchOption.AllDirectories);
IEnumerable<FileInfo> files = fileInfos.Where((f) => f.Extension.Equals(FileExtension)
&& f.Name.StartsWith(Fileprefix)
&& f.CreationTime >= d3
&& f.CreationTime <= d4);
}
In this code...
.Count(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
...x
is a FileInfo
, which doesn't have a DayOfWeek
property. Instead, you need to use whichever of the three *Time
properties of FileInfo
is appropriate; looking at the condition you passed to .Where()
that appears to be CreationTime
...
int count = files.Count(x => x.CreationTime.DayOfWeek != DayOfWeek.Saturday && x.CreationTime.DayOfWeek != DayOfWeek.Sunday);
Alternatively, that code could be made to work by using .Select()
to retrieve just the desired *Time
property...
int count = files
.Select(f => f.CreationTime)
.Count(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
In this case, x
is a DateTime
.
Also, keep in mind the differences between the older GetFiles()
method and the newer EnumerateFiles()
method...
The
EnumerateFiles
andGetFiles
methods differ as follows:
- When you use
EnumerateFiles
, you can start enumerating the collection ofFileInfo
objects before the whole collection is returned.- When you use
GetFiles
, you must wait for the whole array ofFileInfo
objects to be returned before you can access the array.Therefore, when you are working with many files and directories,
EnumerateFiles
can be more efficient.
EnumerateFiles()
is well-suited for this kind of filesystem search/filtering, and, I think, generally the preferred method to use.