将未修改的文件复制到文件夹后删除它们

时间:2013-04-05 15:18:41

标签: vb.net visual-studio-2010

如您所见,以下代码将提取我的“CopierFolderforTestDriveCapstone”文件夹中的所有文件,并将它们全部放在我的“FilesExtracted”文件夹中。我的问题是,在将所有文件放入“FilesExtracted”文件夹后,如何删除最近未修改过的所有文件。我想只保留过去几个月内修改过的文件,或者去年哪一个文件很好。谢谢:))

Imports System.IO

公共类frmExtractionator

Dim txtFiles1 As Control

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click

    Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
    Dim archiveDirectory As String = "E:\FilesExtracted"

    Try
        Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)

        If (Not System.IO.Directory.Exists(archiveDirectory)) Then
            System.IO.Directory.CreateDirectory(archiveDirectory)
        End If

        For Each currentFile As String In txtFiles
            Dim fileName = currentFile.Substring(sourceDirectory.Length + 1)
            File.Move(currentFile, Path.Combine(archiveDirectory, fileName))
        Next
    Catch eT As Exception
        Console.WriteLine(eT.Message)
    End Try

End Sub

1 个答案:

答案 0 :(得分:0)

您可以使用DirectoryInfo类和FileInfo类来获取有关连接到文件的各种时间属性的信息

Try
    Dim di As DirectoryInfo = new DirectoryInfo(sourceDirectory)
    Dim fi as FileInfo() = di.GetFiles()
    .....

    For Each currentFile As FileInfo In fi
        File.Move(currentFile.FullName, Path.Combine(archiveDirectory, currentFile.Name))

        Dim dt As DateTime = currentFile.LastWriteTime
        ' Add 3 months to the last write and check if it is less than today '
        if dt.AddMonths(3) < DateTime.Today then 
            File.Delete(currentFile.FullName)
        End If
    Next
Catch eT As Exception
    Console.WriteLine(eT.Message)
End Try