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

Copy files to new dir and append date

我正在将一些文件(txt/log 个文件)从 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 中。所以,我想在将日期放入文件夹之前将日期附加到日志的末尾。这可能吗?

谢谢

鉴于您的要求,我认为防止多次点击重复过程比附加日期更好:

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,因为现在时间不同