user1269592
user1269592

Reputation: 701

Want to find only files from X last days

I want to search directory and find the files from last x days, currently my function return all the time same file (who created 2 days ago) even if I search more than 2 days.

decimal days = nudDays.Value; 
//read the number from NumericUpDown comtrol

private void setDays() 
//each change in NumericUpDown comtrol will change days variable
{
    if (nudDays.Value != 0)
    {
        days = nudDays.Value;    
    }
    else
    {
        days = decimal.MaxValue;
    }            
}

Checks whether my file created in the last x days (days variable):

public bool checkFileCreationDate(FileInfo fileInfo)
{
    double num = (double)nudDays.Value * -1;
    if (fileInfo.CreationTime > DateTime.Now.AddDays(num))
    {
        return true;
    }

    return false;
}

Upvotes: 2

Views: 1985

Answers (3)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Based on this statement:

currently my function return all the time same file (who created 2 days ago) even if I search more than 2 days.

I believe what you want to do is change this line:

if (fileInfo.CreationTime > DateTime.Now.AddDays(num))

To this:

if (fileInfo.CreationTime == DateTime.Now.AddDays(num))

However, I have to admit, it's not that clear exactly what you're looking for so I hope I interpreted it right.

UPDATE

If you want all files that were created within the past n number of days (i.e. if n were 6 then it would return any files 1-6 days old), then use this:

public bool checkFileCreationDate(FileInfo fileInfo)
{
    double num = (double)nudDays.Value;
    if (DateTime.Now.Subtract(fileInfo.CreationTime).TotalDays <= num)
    {
        return true;
    }

    return false;
}

If you want all files that are n days old (i.e. if n were 6 then it would return any files exactly 6 days old), then use this:

public bool checkFileCreationDate(FileInfo fileInfo)
{
    double num = (double)nudDays.Value;
    if (DateTime.Now.Subtract(fileInfo.CreationTime).TotalDays == num)
    {
        return true;
    }

    return false;
}

Upvotes: 2

Axel Kemper
Axel Kemper

Reputation: 11322

If your time horizon is longer than two days, the file created two days ago will be included. That is ok, because "four days" actually translates into the interval [now-4d .. now]

To exclude your test file, you have to reduce the day number to one.

Be aware that fileInfo.CreationTime and fileInfo.LastWriteTime are different in many cases. You might want to filter for LastWriteTime.

Upvotes: 0

MethodMan
MethodMan

Reputation: 18843

This can be done using linq pass in the Date value that you are looking for

Date somedate;
var filterFiles = from file in directoryInfo.GetFiles() 
            where file.CreationTime > somedate
            select file;

Upvotes: 2

Related Questions