File.Copy
Many ways exist to copy a file. Some are more efficient than others. With File.Copy
in VB.NET we issue an instruction to the operating system.
When we access the operating system with functions like File.Copy
, exceptions are sometimes thrown. We explore the File.Copy
subroutine in VB.NET.
Here we call File.Copy
—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.
File.Copy
sub returns, we call File.ReadAllText
on the original and copied files.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 ModuleHow are you today? How are you today?
For File.Copy
to succeed, the destination file must not exist. You can override
this behavior by passing True as the third argument.
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 ModuleI am well, thank you. I am well, thank you.
A file can be copied by loading it into memory (like with File.ReadAllText
), and then writing that data to a new file. But this involves more than an operating system call.
File.Copy
is usually the better choice, but this is not always true. Sometimes it can be avoided.With File.Copy
the original file must exist. And the destination file must not exist, unless you specify overwriting. It may cause exceptions—using try and catch is worthwhile.