簡體   English   中英

按日期修改在目錄和子目錄中復制文件的最快方法

[英]Fastest way to copy files in directories and sub-directories by datemodified

我想知道我怎么復制文件中包含子目錄的目錄,並在其中包含與修改日期的一些文件。

現在,我需要將所有這些文件復制到另一個目錄。

這就是我復制所有文件和文件夾的內容,但是我只希望從今天前兩天開始修改的文件夾中的文件。 (例如,今天是2014年2月26日。我需要將2014年2月24日及之后的所有文件復制到另一個文件夾中)

  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]

那么誰能說我如何做到這一點呢?

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

這是回答您的查詢的鏈接- 在C#中復制目錄的全部內容

對於您的情況,您必須在執行文件復制之前添加條件。 類似於下面顯示的內容或約翰在回答中使用的內容

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM