Link to home
Start Free TrialLog in
Avatar of John500
John500Flag for United States of America

asked on

Using - Copy(FileToCopy, NewCopy)

Greetings,

I'm trying to copy 1 file 1,000 times so I can use it in testing a particular system.  The code below only copies once without renaming the file with each iteration of the loop:

' Copy the file to a new location without overwriting existing file.
My.Computer.FileSystem.CopyFile( _
    "C:\UserFiles\TestFiles\testFile.txt", _
    "C:\UserFiles\TestFiles2\testFile.txt")

In other words, the same file should be renamed like this each time the copy takes place:

testFile.txt
Copy of testFile.txt
Copy 2 of testFile.txt
...

Are there other versions of CopyFile(...) with parameters that will do what I want or do I need to manipulate the file name to pull this off?  If I have to change the name with each iteration, please provide the solution using Substring() or any other method that will do the job.

Thanks!
Avatar of Brad Brett
Brad Brett
Flag of United States of America image

You will have to check if there is file with the same name exists by using System.IO.File.Exists()

You can also try using:
System.IO.File.Copy(dest1, dest2, True)

Open in new window


Which will throw exception if a file is already exists with the same name.

If the there is a file with the same name you can add "Copy of " to the beginning of the file name.
Avatar of John500

ASKER

I just ended up going this route:

Sub Main()

        Dim check As Boolean = True
        Dim counter As Integer = 0
        Dim DestinationFile As String

        Try

            Do While counter < 1001
                counter += 1
                ' Copy the file to a new location without overwriting existing file.

                DestinationFile = "M:\Test\Sub_Directory\MyFile" + counter.ToString + ".txt"

                My.Computer.FileSystem.CopyFile("M:\Test\MyFile.txt", DestinationFile)

            Loop
        Catch ex As Exception

        End Try

    End Sub

Open in new window

Avatar of John500

ASKER

Any other ideas for something more robust ?  That is, something that will take any file name off the command line along with the destination?

This might be for another question.
Why don't you check if the file is exists using System.IO.File.Exists()?

This way will allow you to change the variable "DestinationFile" and retry to copy again.
ASKER CERTIFIED SOLUTION
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of John500

ASKER

>>Why don't you check if the file is exists using System.IO.File.Exists()?

Well, the file must exist.  I need to create 1000 copies of the same file in the same directory.


wdosanjos,

Although this isn't a VB answer, I have to give you the points for that answer.  That's about as lean as it gets!