To copy the contents of a folder to an other folder, including all subfolders, overwriting existing files, you can use the following function in C#:

 

/// <summary>
/// Copies the contents of a folder, including subfolders to an other folder, overwriting existing files
/// </summary>
/// <param name="sourceFolder"></param>
/// <param name="destinationFolder"></param>
public static void CopyFolderContents(string sourceFolder, string destinationFolder)
{
    if (Directory.Exists(sourceFolder))
    {
        // Copy folder structure
        foreach (string sourceSubFolder in Directory.GetDirectories(sourceFolder, "*", SearchOption.AllDirectories))
        {
            Directory.CreateDirectory(sourceSubFolder.Replace(sourceFolder, destinationFolder));
        }

        // Copy files
        foreach (string sourceFile in Directory.GetFiles(sourceFolder, "*", SearchOption.AllDirectories))
        {
            string destinationFile = sourceFile.Replace(sourceFolder, destinationFolder);
            File.Copy(sourceFile, destinationFile, true);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.