Home > Code > File Handling > How to copy all files from one folder to another folder using C#

How to copy all files from one folder to another folder using C#

by Thamil   on Sep 11, 2013   Category: File Handling   |  Views: 26381    |  Points: 25   |  Gold 



Below is the sample code for copying all files from one folder to another folder in a simple way. if file is exist in target folder then it will overwrite the file.

using System.IO;

string sourcePath = @"D:\test";
string targetPath = @"D:\test_new";
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
foreach (var srcPath in Directory.GetFiles(sourcePath))
{
//Copy the file from sourcepath and place into mentioned target path,
//Overwrite the file if same file is exist in target path
File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true);
}




Post Code  |  Code Snippet Home

User Responses


  Re :How to copy all files from one folder to another folder using C#   
Posted by Samba067
on 03/06/2015
Points : 5

Hi Boss , This is not Executed.. so copy the correct code,useful to all others.
  Re :How to copy all files from one folder to another folder using C#   
Posted by ThamilselvanJ
on 04/06/2015
Points : 5

Dear samba,

Can you provide me the error details which you are getting.
  Re :How to copy all files from one folder to another folder using C#   
Posted by Ericderp
on 24/11/2016
Points : 5

//It needs a namespace, class and main program to execute, along with three closing parentheses. Thanks for the code you posted.

using System.IO;

namespace CopyFiles
{
class Program
{
static void Main(string[] args)
{

string sourcePath = @"D:\test";
string targetPath = @"D:\test_new";
if (!Directory.Exists(targetPath))

{
Directory.CreateDirectory(targetPath);
}

foreach (var srcPath in Directory.GetFiles(sourcePath))
{
//Copy the file from sourcepath and place into mentioned target path,
//Overwrite the file if same file is exist in target path
File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true);
}

}
}
}

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts