Reputation: 7324
I have a directory structure with txt files.
I want to get a list of file names where the modified/creation date is between a range.
So far, I have this:
DirectoryInfo directory = new DirectoryInfo(@"C:\MotionWise\Manifest\000EC902F17F");
DateTime from_date = DateTime.Now.AddMinutes(-300);
DateTime to_date = DateTime.Now;
List<FileInfo> files = directory.GetFiles("*", SearchOption.AllDirectories).Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date).ToList();
Now,I am only interested in the full path name.
If I enumerate through the files list I can add the full path name to a new list/array etc. but this seems a waste of extra effort as I feel there is a way to do this in the lambada code?
If it can be done in the lambada code will not the selection by file info be too 'heavy'? Is there a way to just select full path name without 'loading' each entry into a file info?
I have been toying with the idea of executing the dir DOS command and capturing the output in the Process class.
Upvotes: 1
Views: 3088
Reputation: 460138
If you're only interested in the paths don't use DirectoryInfo.GetFiles
because it returns an array and because it is a FileInfo[]
where each FileInfo
object includes all informations that you're not interested in anyway. You can use File.GetLastWriteTime
to get it.
Instead use Directory.EnumerateFiles
which lazily returns only paths that are matching your filter criteria and the search pattern.
List<string> paths = Directory.EnumerateFiles(@"C:\MotionWise\Manifest\000EC902F17F", "*", SearchOption.AllDirectories)
.Where(path => {
DateTime lastWriteTime = File.GetLastWriteTime(path);
return lastWriteTime >= from_date && lastWriteTime <= to_date;
})
.ToList();
Upvotes: 5
Reputation: 6304
Just Select
on the FullName
:
List<string> files = directory.GetFiles("*", SearchOption.AllDirectories)
.Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date)
.Select(f => f.FullName)
.ToList();
Upvotes: 4