C# - How to copy files and overwriting existing files if exists in a folder by using C Sharp

Scenario: Download Script

You are working as C# developer and you need to write a program that should copy all the files from a folder to another folder, In case files already exists, you want to overwrite with new file from source folder.

Below script can be used to copy all the files from a folder to another folder and overwrite if exists.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            //Provider Source Folder Path
            string SourceFolder = @"C:\Source\";
            //Provide Destination Folder path
            string DestinationFolder = @"C:\Destination\";
            
           var files = new DirectoryInfo(SourceFolder).GetFiles("*.*");
      
            //Loop throught files and copy to destination folder, overwrite if exists
          foreach (FileInfo file in files)
            {
                file.CopyTo(DestinationFolder + file.Name,true);
            }
            
        }
    }
}

No comments:

Post a Comment