C# - How to Copy files from a folder to another folder and add date-time to file names in C Sharp

Scenario: Download Script

You are working as C# developer, you need to write a program that should copy the files from a folder to another folder, while it copies the file, it should add date-time to each file name it copies to destination folder.


Below C# Script can be used to copy all the files from a folder to another folder and add date-time to destination copied file names.


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)
        {

            try
            {
                //Provider Source Folder Path
                string SourceFolder = @"C:\Source\";
                //Provide Destination Folder path
                string DestinationFolder = @"C:\Destination\";

                //datetime variable to use as part of file name
                string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");

                var files = new DirectoryInfo(SourceFolder).GetFiles("*.*");

                //Loop throught files and Copy to destination folder
                foreach (FileInfo file in files)
                {

                    string fileExt = "";
                    fileExt = Path.GetExtension(file.Name);

 //Copy the file to destination folder after adding datetime
 file.CopyTo(DestinationFolder + file.Name.Replace(fileExt,"") + "_" + datetime + fileExt);

                }

            }
            catch(IOException Exception)
            {
                Console.Write(Exception);
            }
            }

    }
}

1 comment:

  1. Thanks for this excellent code , and also you can directly use Goodsync or Gs Richcopy 360 to do this job

    ReplyDelete