What is the best way to copy multiple files but only copy them if there is no errors for all of them?

Cynolycus 255 Reputation points

Currently my program copies files one at a time if it detects that a particular file has been saved.

This is fine as long as there is no error for any file.

Some files are only read when the external program starts, others are changed on occasion, but the one that is being watched always changes when a change is made to any of the other files, which is why I picked that file to watch.

To test my test program I have a text file that is being watched open in Notepad and when I save it all works well but when the code was placed in the program that I am creating and I opened the real file that needs to be watched and saved it it threw an error. The same happened when I changed the test program to use the real files.

It detected that the file was open in Notepad.

I had this problem about four hours ago but for some reason it is not doing it now and nothing has been changed, it just copies the file even though it is open in Notepad.

Anyway this led me to another potential problem, these files are dependent on each other, they are a set and must all be copied or none at all.

If I can do this then it will also solve my initial problem if it decides to come back.

I placed the line that copies the file inside a Try/Catch statement.

If File.Exists(SourceDirectory & "\" & FileToCheck) Then
        My.Computer.FileSystem.CopyFile(SourceDirectory & "\" & FileToCheck, BackupDirectory & "\" & Now.ToString("dd.MM.yyyy_HH.mm.ss") & ".txt")
    Catch ioException As IOException
        'The specified file is in use.

    Catch ex As Exception
        'Some other error apart from file in use.

    End Try
End If

This is fine if all I needed was to detect an error with a single file, but I am copying several files from different locations.

I could do the same thing for all files which would stop the program from crashing but as I said they must all be copied or none at all, and doing it that way some files could be copied but others may not.

I don't really need to know what the error is, just that the file can't be copied and if a file can't be copied then I want it to try again.

How to try again is another thing that I don't know how to do, but I haven't looked into that yet.

I have never tried this before but my thoughts were to do something like Microsoft has in Handling multiple exceptions in async methods.


One concern with this was that by the time all checks were done another process may have started doing something with one of the files. The time taken to do the checks may be that short that this isn't anything to worry about.

Is Handling multiple exceptions in async methods the way this should be done, and if so do I put

My.Computer.FileSystem.CopyFile(SourceDirectory & "\" & FileToCheck, BackupDirectory & "\" & Now.ToString("dd.MM.yyyy_HH.mm.ss") & ".txt")

in place of "info:" in the following line

Dim theTask1 As Task = ExcAsync(info:="First Task")

or is there a better way to copy these files?

I'm probably trying to put too much in this program for my level of understanding, but I'm learning as I go, and unfortunately as I go I'm finding more things to put in and better ways to do what I've just done. Luckily I'm near the end.

I thank all those that have helped me so far and those that help in the future.

An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,394 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 21,706 Reputation points Microsoft Vendor

    Hi @Cynolycus ,

    Use CopySuccess as a semaphore to record the success of the copy operation.

    Create two lists, FilesToCopy and FilesCopied, to store the files that need to be copied and the directories that have been copied successfully.

    Use a Do... Loop construct, which runs until the CopySuccess variable is True. Within the loop, try to copy the file. If an error occurs during the replication process, the copied files are deleted and the entire replication process is restarted until all files have been successfully copied.

    Dim sourceDirectory As String = "sourceDirectory"
            Dim destinationDirectory As String = "destinationDirectory"
            Dim filesToCopy As String() = {"file1.txt" , "file2.txt" , "file3.txt", ...}
            Dim copySuccess As Boolean = False
                Dim filesCopied As New List(Of String)()
                    For Each file As String In filesToCopy
                        Dim sourceFile As String = Path.Combine(sourceDirectory, file)
                        Dim destinationFile As String = Path.Combine(destinationDirectory, file)
                        File.Copy(sourceFile, destinationFile, True)
                    Console.WriteLine("All files have been copied successfully.")
                    copySuccess = True
                Catch ex As Exception
                    Console.WriteLine($"Error copying: {ex.Message}")
                    For Each copiedFile As String In filesCopied
                            If File.Exists(copiedFile) Then
                                Console.WriteLine($"File deleted: {copiedFile}")
                            End If
                        Catch deleteEx As Exception
                            Console.WriteLine($"Error deleting: {deleteEx.Message}")
                        End Try
                End Try
            Loop While Not copySuccess

    Best Regards.

    Jiachen Li

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

0 additional answers

Sort by: Most helpful