How to copy files into a directory in C#?


To Copy a file, C# provides a method File. Copy

File. Copy has 2 overloads

Copy(String, String) -Copies an existing file to a new file. Overwriting a file of the same name is not allowed.

Copy(String, String, Boolean) Copies an existing file to a new file. Overwriting a file of the same name is allowed.

Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories.

Example

static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1";

   var searchSourceFolder = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly);
   Console.WriteLine("-------------Source Folder-------------");
   foreach (string file in searchSourceFolder){
      Console.WriteLine(file);
   }

   string destinationFolder = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\";

   var destinationFolderFiles = Directory.GetFiles(destinationFolder, "*.*",    SearchOption.TopDirectoryOnly);
   Console.WriteLine("-------------Destination Folder Before Copying-------------");
   foreach (string file in destinationFolderFiles){
      Console.WriteLine(file);
   }

   string[] files = Directory.GetFiles(rootPath);

   foreach (string file in files){
      File.Copy(file, $"{destinationFolder}{ Path.GetFileName(file) }");
   }
   Console.WriteLine("-------------After Copying-------------");

   var destinationFolderAfterCopyingFiles = Directory.GetFiles(destinationFolder, "*.*",    SearchOption.TopDirectoryOnly);

   foreach (string file in destinationFolderAfterCopyingFiles){
      Console.WriteLine(file);
   }
   Console.ReadLine ();
}

Output

-------------Source Folder-------------
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1\TestFolderMain1.txt
-------------Destination Folder Before Copying-------------
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt
-------------After Copying-------------
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain1.txt
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt

Updated on: 25-Nov-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements