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.
Subroutine notes. When we access the operating system with functions like File.Copy, exceptions are sometimes thrown. We explore the File.Copy subroutine in VB.NET.
Example. 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.
Then After the 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?
Overwrite. For File.Copy to succeed, the destination file must not exist. You can override this behavior by passing True as the third argument.
And This eliminates the "already exists" exception. The previous contents of the destination file are lost.
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 discussion. 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.
However We may need to do further processing on the file. In this case it may be more efficient to just write the in-memory version to the disk.
Tip Using File.Copy is usually the better choice, but this is not always true. Sometimes it can be avoided.
A summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 24, 2022 (edit link).