将文件复制到新目录并附加日期

时间:2016-05-20 09:36:11

标签: vb.net visual-studio-2010

我正在将一些文件(txt /日志文件)从C:\ Application \ Logs \ Log.txt(和Log2.txt等)复制到C:\ Logs

代码:

If Not File.Exists("C:\Logs\Log.txt") Then
                My.Computer.FileSystem.CopyFile(
        "C:\Application\Logs\Log.txt",
        "C:\Logs\Log.txt")
            End If

如果多次按下该按钮,则会失败,因为日志已存在于C:\ Logs中。所以,我想在将日期放入文件夹之前将日期附加到日志的末尾。这可能吗?

由于

1 个答案:

答案 0 :(得分:1)

根据您的要求,我认为防止多次点击制作重复流程比附加日期更好:

Dim isProcessed As Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If isProcessed Then
        Return
    End If
    isProcessed = True

    If Not File.Exists("C:\Logs\Log.txt") Then
        My.Computer.FileSystem.CopyFile(
          "C:\Application\Logs\Log.txt",
          "C:\Logs\Log.txt")
    End If

    isProcessed = False
End Sub

然而,如果你想添加DateTime,你可以通过在日志文件名中附加DateTime.Now.ToString("yyyyMMdd_HHmmss_fff")作为文本来实现这一点:

Dim isProcessed As Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If isProcessed Then
        Return
    End If
    isProcessed = True

    Dim filename As String = "C:\Logs\Log_" & DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") & ".txt"
    My.Computer.FileSystem.CopyFile("C:\Application\Logs\Log.txt", filename)

    isProcessed = False
End Sub

不再需要支票If Exist,因为现在时间不同