Reputation: 2013
I have an issue to get some files with a range of date. I searched here and found many answers, but i can't solve my problem.
So, I have this method to get those files:
DateTime fromDate = tpFrom.Value;
DateTime toDate = tpTo.Value;
var files = new DirectoryInfo(origemPath).GetFiles()
.Where(
f => f.CreationTime.Date >= fromDate &&
f.CreationTime.Date <= toDate);
foreach (var file in files)
{
...
}
But that get all files, ignoring the where...
fromDate and toDate is a value from a DateTimePicker
Debuging
One file in files:
fromDate value:
EDIT:
I tried all the answers here, and nothing worked. How I don't need the best performatic method, I solved my problem like this:
var files = new DirectoryInfo(origemPath).GetFiles();
foreach (var file in files)
{
if (file.CreationTime.Date >= fromDate && file.CreationTime.Date <= toDate)
{
...
}
}
Upvotes: 1
Views: 160
Reputation: 21
Try something like this:
private List<string> GetFiles(DateTime toDate, DateTime fromDate, string directoryName)
{
if (toDate > fromDate)
{
List<string> list = Directory.GetFiles(directoryName).ToList();
return list.Where(f => File.GetCreationTime(f) <= toDate && File.GetCreationTime(f) => fromDate).ToList();
}
return new List<string>();
}
Upvotes: 1
Reputation: 3626
private List<string> GetFiles(DateTime toDate, DateTime fromDate, string directoryName)
{
if (toDate > fromDate)
{
List<string> list = Directory.GetFiles(directoryName).ToList();
return list.Where(f => File.GetCreationTime(f) <= toDate && File.GetCreationTime(f) => fromDate).ToList();
}
return new List<string>();
}
Upvotes: 1
Reputation: 1326
I think that the Where clause does not execute, check this link. to find out more details about it. In LINQ, execution of a query is usually deferred until the moment when you actually request the data. In the line with files.Count() you actually get the values. Check out more about LINQ and dererred execution.
You should try something like the following:
DirectoryInfo diInbox = new DirectoryInfo(location);
FileInfo[] InboxFiles = diInbox.GetFiles();
var files = from file in InboxFiles
where file.CreationTime >= FromDate
select file;
foreach (var file in files){...}
Upvotes: 0
Reputation: 5723
If tpFrom and tpTp are Pickers, maybe the following will do the job
DateTime fromDate = tpFrom.Value.Date;
DateTime toDate = tpTo.Value.Date;
Upvotes: 1