Home > Mobile >  C# LINQ query to get file created between certain dates
C# LINQ query to get file created between certain dates

Time:10-01

i am trying to write a LINQ query to get only files with a creation date between certains dates, but it isn't working. Here's my code:

string startFolder = @"C:\Users\gforl\Downloads\";

        //Oldest date
        DateTime dateToCheck = DateTime.Now.AddDays(-5);

        // Take a snapshot of the file system.  
        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);

        // This method assumes that the application has discovery permissions  
        // for all folders under the specified path.  
        IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.mp4", System.IO.SearchOption.AllDirectories);

        //Create the query  
        IEnumerable<System.IO.FileInfo> fileQuery =
            from file in fileList
            where file.CreationTime.Millisecond >= dateToCheck.Millisecond
            orderby file.CreationTime descending
            select file;

        //Execute the query. This might write out a lot of files!  
        foreach (System.IO.FileInfo fi in fileQuery)
        {
            Console.WriteLine(fi.FullName);
        }

Any suggestion to solve the problem? Thanks

CodePudding user response:

Found a solution!

where DateTime.Compare(file.CreationTime, dateToCheck) >= 0

CodePudding user response:

The milliseconds just return the milliseconds part of DateTime. The correct solution will be:
where file.CreationTime.Ticks >= dateToCheck.Ticks

  • Related