0
votes

I would like to know how do I copy the files in a directory which contains sub directories and in them it contains some files with date modified.

Now I need to copy all those files to another directory.

This is what I have which copies all the files and folders but I want only the files in folders which are modified from two days before todays date. (For ex: today date is 26-02-2014. I need to copy all the files from 24-02-2014 and below that date to another folder)

  Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
    Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)

    ' If the destination folder don't exist then create it
    If Not System.IO.Directory.Exists(destinationPath) Then
        System.IO.Directory.CreateDirectory(destinationPath)
    End If

    Dim fileSystemInfo As System.IO.FileSystemInfo
    For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
        Dim destinationFileName As String =
            System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)

        ' Now check whether its a file or a folder and take action accordingly
        If TypeOf fileSystemInfo Is System.IO.FileInfo Then
            System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
        Else
            ' Recursively call the mothod to copy all the neste folders
            CopyDirectory(fileSystemInfo.FullName, destinationFileName)
        End If
    Next
End Sub

And this is the code which copies only files in a folder and dosent add any new folder which is in source path:

Dim Source As New DirectoryInfo("C:\Users\username\Desktop\123")
    Dim Target As New DirectoryInfo("C:\Users\username\Desktop\345")

    Dim Files As FileInfo() =
        (From [File] As FileInfo In Source.GetFiles("*", SearchOption.AllDirectories)
         Where [File].LastWriteTime.Date.Equals(Date.Today.AddDays(-2))).ToArray

    For Each [File] As FileInfo In Files
        IO.File.Copy([File].FullName, 
                     Path.Combine(Target.FullName, [File].Name), True)
    Next [File]

So can anyone say how do I acheive this?

2

2 Answers

0
votes

In c#, the File object has methods to determine modification date. So, you could do something like this:

DateTime today = DateTime.Today;
foreach (string filename in Directory.GetFiles("C:\\Users\\username\\Desktop\\123")) {
    DateTime fileModDate = File.GetLastWriteTime(filename);
    if (fileModDate < today.AddDays(-2)) {
        File.Copy(filename, destination);
    }
}
0
votes

Here is a link that answers your query - Copy the entire contents of a directory in C#

In your case you would have to add a condition before doing a File Copy. Something like the one shown below or the one used by John in his answer

    if (File.GetLastWriteTime(path).CompareTo(DateTime.Today) <= -2)
    {
    ...
    }