Quantcast
Channel: Welcome To TechBrothersIT
Viewing all articles
Browse latest Browse all 1976

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

$
0
0

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
{
staticvoid 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);
}
}

}
}

Viewing all articles
Browse latest Browse all 1976

Trending Articles