通过datemodified复制目录和子目录中文件的最快方法

时间:2014-02-26 18:07:05

标签: c# vb.net file copy subdirectory

我想知道如何将文件复制到包含子目录的目录中,其中包含一些日期已修改的文件。

现在我需要将所有这些文件复制到另一个目录。

这就是我所拥有的复制所有文件和文件夹但我只想要在今天日期前两天修改的文件夹中的文件。 (例如:今天的日期是2014年2月26日。我需要将所有文件从24-02-2014及以下日期复制到另一个文件夹)

  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

这是只复制文件夹中文件的代码,并且可以添加源路径中的任何新文件夹:

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]

所以有人可以说我如何实现这个目标?

2 个答案:

答案 0 :(得分:0)

在c#中,File对象具有确定修改日期的方法。所以,你可以这样做:

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);
    }
}

答案 1 :(得分:0)

以下是一个回答您的查询的链接 - Copy the entire contents of a directory in C#

在您的情况下,您必须在执行文件复制之前添加条件。类似于下面显示的那个或John在他的回答中使用的那个

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