Search code examples
c#datetimedirectory-structure

C# Copy file with specify date and time range


In Visual C#:

I wish to copy a list of file(s) of specify range of date and time from 1 folder to another. I keep getting all files instead of just the file I want.

E.g:

20th Feb 2019 2am to 2nd March 2019 1am (Base on Date time modified)

Copy

D:\Data\SubFolder1\SubFolder2\SubFolder3\\*.log

to

E:\MyLogs\D\Data\SubFolder1\SubFolder2\SubFolder3\

What function or library should I be looking at?


Solution

  • You can try code like below

    Import System.IO to use DirectoryInfo from it.

    I am also importing System.Linq to use Where method from it.

    Say you have your directorypath in a variable say yourDirectoryPath

    // Specify the directory you want to use
    DirectoryInfo directory = new DirectoryInfo(yourDirectoryPath);
    // Check if your directory exists and only then proceed further
    if (directory.Exists){
        //You would be having your fromdate and toDate in two variables like fromDate, toDate
        // files variable below will have all the files that has been lastWritten between the given range
        var files = directory.GetFiles()
                     .Where(file=>file.LastWriteTime >= fromDate && file.LastWriteTime <= toDate);
     }
    

    Now you can use your existing code (let me know in case you didnt) to copy all the files from the folder to the destination.