Chrome Extension

How to copy files from source to destination in c#?

I want to copy files from one folder to another using c#. The path of the folders are as below

String sourceFolder = @"C:\Users\Desktop\Source";

String destinationFolder = @"C:\Users\Desktop\Destination";

Please provide the code to copy files from sourceFolder to destinationFolder

2 Answers

To copy files from source to destination you can use below c# code

public class FileCopy
{
    static void Main()
    {
        string fileName = "myFile.txt";
        string sourceFolder = @"C:\Users\Desktop\Source";
        string destinationFolder = @"C:\Users\Desktop\Destination";

        //GET FULL FILE PATH(SOURCE AND DESTINATION)
        string sourceFilePath = System.IO.Path.Combine(sourceFolder, fileName);
        string destinationFilePath = System.IO.Path.Combine(destinationFolder, fileName);

        //CREATE DESTINATION DIRECTORY IF NOT EXIST
        //NOTE - IT WILL NOT CREATE NEW DIRECTORY IF IT ALREADY EXIST
        System.IO.Directory.CreateDirectory(destinationFolder);
        
        //COPY SOURCE FILE TO DESTINATION
        //NOTE - IT WILL OVERRITE THE FILE IF IT ALLREADY EXISTS ON THE DESTINATION FOLDER
        System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
        
        Console.WriteLine("This will keep your cmd window open");
        Console.ReadKey();
    }
}

The above code will copy file named myFile.txt which exists inside 'sourceFolder' to the folder named as 'destinationFolder'.

We use System.IO for this purpose which is commonly used for input output file operations like creating directories, copying files, moving files, deleting files, etc in C#

To copy files one location to another location in C#, simply use below code

System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
Search history ×