What is File.Copy() in C#?

Overview

File.Copy() is a file class method that copies the contents of a file to a file that is created by this function.

Syntax

File.Copy(string source, string destination)

Parameters

  • source: This is the name of the file whose contents we want to copy.

  • destination: This is the file that will be created by the File.Copy() method and filled with the contents of the file with the name source.

Example

Let’s look at the code below:

main.cs
test1.txt
Welcome to Edpresso!

Explanation

First, we create a file called test1.txt and write "Welcome to Edpresso!" inside it.

  • Lines 13 and 14: We get the file names.
  • Line 17: We copy file1 to file2.
  • Line 19: We print a success message if file copying is successful.
  • Lines 23 and 24: We print out the file contents to ensure success.

Free Resources