How to copy files from a folder to another folder and rename with datetime using C#

Intro: 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 dataworldwithgbengaoridupa.com_CSharp_Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                //Provide your source folder path here
                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 through 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);
            }
            }

    }

}

Comments

Popular posts from this blog

AWS: Benefits of using Amazon S3

Google To Acquire Looker For $2.6 Billion

Python - GUI - Tkinter(Bar & Pie Chart)