Jeremy Jeremy - 6 months ago 24
Vb.net Question

Copy files to new dir and append date

I'm copying over some files (txt/log files) from C:\Application\Logs\Log.txt (and Log2.txt etc) to C:\Logs

Code:

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


If the button is pressed multiple times, this will fail as the logs already exist in C:\Logs. So, I would like to append date to the end of the log before it is placed in the folder. Is this possible?

Thanks

Ian Ian
Answer

Given your requirement, I think it will be better to prevent the multiple clicks to make duplicate process than to append the date:

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

Nevertheless, if you want to add the DateTime, you could do that by having DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") appended as text in your log file name too:

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

The check If Exist is no longer needed, since the time is different now