C# code to Copy file from One Folder to Another

We use File.Copy method in C# to copy a file from one directory to another directory. This method takes three parameters.

1: SourceFileName: Existing file name with full existing path name

2: DestinationFileName: New file name with full destination path name. If you want to rename the file while copying to new location, you need to provide the new name or if you want to copy with the existing name, you need to provide existing name.

3: The third parameter is optional and is set to true. It is used when you want to overwrite the file if it already exists on destination path.

Follow the below given steps to copy file from source path to destination path.

Step1: Use this namespace at the starting of your code.

using System.IO;

Step 2: Define the function as below.

public void copyFile()
{
    string sourcePath = @"D:\Source Folder\FileToBeCopied.txt";
    string targetPath = @"D:\Destination Folder\FileToBeCopied.txt";
    string targetPathDir = @"D:\Destination Folder\";

   // Creates target directory if it does not exists
    if (!Directory.Exists(targetPathDir))
    {
      Directory.CreateDirectory(targetPathDir);
    }

    // code to copy file
    try
    {
      File.Copy(sourcePath, targetPath, true);
    }
    catch (Exception ex)
    {

    }

}

The above code snippet shows how to copy file from on location to another using C#.

Leave a Reply