C# - How to move and rename files to another folder by adding datetime to file name by C Sharp

Scenario: Download Script

You are working as C# developer, you need to create a program that should move all the files from a folder to destination folder. While it moves the files, it should rename the files and add datetime to each file.

The C# code can be used to move and rename files from a folder to another folder and will add date-time to each file.


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 Move to destination folder
                foreach (FileInfo file in files)
                {

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

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

                }

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

    }
}

No comments:

Post a Comment