just peter
just peter

Reputation: 125

Returning size of files based on selected date range

I have a function where it suppose to return size of files within specified range, however, it goes thru all of the files in the directory and not those between date ranges, using linq method: is this even correct way of doing it?

public static long fileSize(string source_path)
{
     return new DirectoryInfo(source_path)
             .EnumerateFiles("*.SS*")
             .Where(file => file.CreationTime < dt.AddMonths(-2))
             .Sum(file => file.Length);
}

Upvotes: 0

Views: 63

Answers (1)

Geoff James
Geoff James

Reputation: 3180

OK, so I've just spent a little time trialling your code.

I couldn't see why it wouldn't work, so I split out the code into separate lines. It appears that the long Linq function is confusing itself.

Below is what worked for me.

It is essentially exactly the same as what you were doing before, just declaring some local variables as way-points to make sure things are as they should be at certain points:

public static long FileSize(string path)
{
    var di = new DirectoryInfo(path);
    var allFiles = di.EnumerateFiles(); // Enter your filter "*.SS" or whatever

    var beforeDate = DateTime.Now.AddMonths(-2);

    var olderThan2Months = allFiles.Where(x => x.CreationTime < beforeDate);

    return olderThan2Months.Sum(x => x.Length);
}

This worked a charm for me (obviously you can change the variables to more meaningful names).

Here's a sample screenshot of the above code working
(I only used Downloads folder, and didn't filter the files):

Sample screenshot!

I used the above code to filter by older than 2 months, and a "GetAll" to compare the 2 and make sure it worked - trust me I made sure it does :)

Hope this helps!

Upvotes: 1

Related Questions