Link to home
Create AccountLog in
Avatar of taz8020
taz8020Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Get all Files in directory but that are newer than a date

Hi I want to loop through each file in a directory that are newer than a date.

This is the long way I do things at the moment.

For Each fi As FileInfo In di.GetFiles

If fi.CreationTime > MyDate and fi.Extension = ".cdr" then
'do something
 End If

 Next
Avatar of YZlat
YZlat
Flag of United States of America image

For Each fi As FileInfo In di.GetFiles("*.cdr")
       If fi.CreationTime > MyDate then
               'do something
         End If
 Next 

Open in new window

Hi,

Try
var directory = new DirectoryInfo(@"c:\");
DateTime MyDate = DateTime.Now.AddMonths(-1);
var files = directory.GetFiles("*.cdr").Where(file => file.CreationTime >= MyDate);

Open in new window

Avatar of taz8020

ASKER

Hi rajapandian_81 that look just like what I am after on a few functions I need a date range

eg Date greater than and date less than

Using you way how would I do this, would it be like:

var directory = new DirectoryInfo(@"c:\");
DateTime MyDate1 = DateTime.Now.AddMonths(-2);
DateTime MyDate2 = DateTime.Now.AddMonths(-1);
var files = directory.GetFiles("*.cdr").Where(file => file.CreationTime >= MyDate1 And file.CreationTime <= MyDate2);
Nothing wrong with the original code in my opinion...

You can use LINQ for a "one-liner":
        For Each file As FileInfo In (From fi In di.GetFiles Select fi Where fi.CreationTime > myDate And fi.Extension.ToLower = ".cdr")
            Debug.Print(file.FullName)
        Next

Open in new window

Same thing with the date range:
        For Each file As FileInfo In (From fi In di.GetFiles Select fi _
                                      Where fi.CreationTime >= startDate AndAlso fi.CreationTime <= stopDate _
                                      AndAlso fi.Extension.ToLower = ".cdr")
            Debug.Print(file.FullName)
        Next

Open in new window

Hi,

For date range, use the following code:
var directory = new DirectoryInfo(@"c:\");
DateTime MyDate1 = DateTime.Now.AddMonths(-2);
DateTime MyDate2 = DateTime.Now.AddMonths(-1);
var files = directory.GetFiles("*.cdr").Where(file => file.CreationTime >= MyDate1 && file.CreationTime <= MyDate2);

Open in new window

Avatar of taz8020

ASKER

sorry to be a pain one last thing how would you sort by oldest first
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account