Open In App

File.Copy(String, String) Method in C# with Examples

File.Copy(String, String) is an inbuilt File class method that is used to copy the content of the existing source file content to another destination file which is created by this function.
 

Syntax:  



public static void Copy (string sourceFileName, string destFileName);

Parameter: This function accepts two parameters which are illustrated below:  

  • sourceFileName: This is the file from where data is copied.
  • destFileName: This is the file where data is pasted. This cannot be a existing file or a directory.

Exceptions: 



Below are the programs to illustrate the File.Copy(String, String) method.
Program 1: Before running the below code, only source file file.txt was created which is shown below. Below code itself creates a destination file gfg.txt and copies the source file contents to the destination file.
 




// C# program to illustrate the usage
// of File.Copy() method
  
// Using System, System.IO,
// System.Text and System.Linq namespaces
using System;
using System.IO;
using System.Text;
using System.Linq;
  
class GFG {
    // Main() method
    public static void Main()
    {
        // Creating two files
        string sourceFile = @"file.txt";
        string destinationFile = @"gfg.txt";
        try {
            // Copying source file's contents to
            // destination file
            File.Copy(sourceFile, destinationFile);
        }
        catch (IOException iox) {
            Console.WriteLine(iox.Message);
        }
        Console.WriteLine("Copying process has been done.");
    }
}

Executing:

mcs -out:main.exe main.cs
mono main.exe
Copying process has been done.

After running the above code, above output has been shown and a new destination file gfg.txt created which is shown below:
 

Program 2: Before running the below code, two file is created with some contents shown below:
 

 




// C# program to illustrate the usage
// of File.Copy() method
  
// Using System, System.IO,
// System.Text and System.Linq namespaces
using System;
using System.IO;
using System.Text;
using System.Linq;
  
class GFG {
    // Main() method
    public static void Main()
    {
        // Specifying two files
        string sourceFile = @"file.txt";
        string destinationFile = @"gfg.txt";
        try {
            // Copying source file's contents to
            // destination file
            File.Copy(sourceFile, destinationFile);
        }
        catch (IOException iox) {
            Console.WriteLine(iox.Message);
        }
    }
}

Executing: 

mcs -out:main.exe main.cs
mono main.exe
Could not create file "/home/runner/NutritiousHeavyRegression/gfg.txt". File already exists.

After running the above code, the above error is thrown because the destination file was created before running the program.


Article Tags :
C#