HomeSearch

VB.NET File.Copy: Examples, Overwrite

Use the File.Copy subroutine to copy one file to another location.
File.Copy. Many ways exist to copy a file. Some are more efficient than others. With File.Copy we issue an instruction to the operating system. Exceptions are sometimes thrown. We explore the File.Copy subroutine in VB.NET.File
Example. In this VB.NET program we call File.Copy on a local file. The file specified must be found in the program's directory. If it is not found, an exception will be thrown. The file must exist for the copy to succeed.

Then: After the File.Copy sub returns, we call File.ReadAllText on the original and copied files.

Finally: We display the contents of both files to show that the destination file has the same contents as the original.

Contents, file-a.txt: How are you today? VB.NET program that uses File.Copy Imports System.IO Module Module1 Sub Main() ' Copy one file to a new location. File.Copy("file-a.txt", "file-b.txt") ' Display file contents. Console.WriteLine(File.ReadAllText("file-a.txt")) Console.WriteLine(File.ReadAllText("file-b.txt")) End Sub End Module Output How are you today? How are you today?
Overwrite. For File.Copy to succeed, the destination file must not exist. You can override this behavior by passing True as the third argument. This eliminates the "already exists" exception. The previous contents of the destination file are lost.
Contents 2, file-a.txt: I am well, thank you. VB.NET program that overwrites, copies Imports System.IO Module Module1 Sub Main() ' Allow the destination to be overwritten. File.Copy("file-a.txt", "file-b.txt", True) ' Display. Console.WriteLine(File.ReadAllText("file-a.txt")) Console.WriteLine(File.ReadAllText("file-b.txt")) End Sub End Module Output I am well, thank you. I am well, thank you.
Discussion. A file can be copied by loading it into memory, and then writing that data to a new file. The File.ReadAllText sub could be used for this. But File.ReadAllText is slower—it involves more than an operating system call.
However, you may need to do further processing on the file. Here, it may be more efficient to just write the in-memory version to the disk, skipping File.Copy. Using File.Copy is usually the better choice, but this is not always true.

Thus: Optimization guidelines always depend on many factors. A programmer must be able to decide based on program context.

Summary. File.Copy is a powerful sub. But it has some complexity. The original file must exist. And the destination file must not exist, unless you specify overwriting. File IO code may cause exceptions, so using try and catch is worthwhile.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls