Open In App

C# – Copying the Contents From One File to Another File

Given a file, now our task is to copy data from one file to another file using C#. So to do this task we use the Copy() method of the File class from the System.IO namespace. This function is used to copy content from one file to a new file. It has two different types of overloaded methods:

1. Copy(String, String): This function is used to copy content from one file to a new file. It does not support overwriting of a file with the same name. 



Syntax:

File.Copy(file1, file2);

Where file1 is the first file and file2 is the second file. 



Exceptions: This method will throw the following exceptions:

2. Copy(String, String, Boolean): This function is used to copy content from one file to a new file. It does not support overwriting of a file with the same name. 

Syntax:

File.Copy(file1, file2, owrite);

Where file1 is the first file, file2 is the second file, and write is a boolean variable if the destination file can be overwritten then it is set to true otherwise false. 

Exceptions: This method will throw the following exceptions:

Example:

Let us consider two files named file1 and file2. Now the file1.txt contains the following text:

Now the file2.txt contains the following text:

Approach:

  1. Place two files in your csharp executable folder in your system.
  2. In the main method use File.Copy() to copy contents from first file to second file.
  3. Display the text in file2 using File.ReadAllText() method.




// C# program to copy data from one file to another
using System;
using System.IO;
  
class GFG{
      
static void Main()
{
    
    // Copy contents from file1 to file2
    File.Copy("file1.txt", "file2.txt");
      
    // Display file2 contents
    Console.WriteLine(File.ReadAllText("file2.txt"));
}
}

Output:

Now, file2.txt is:


Article Tags :