How to copy a file in C#

File class provides functionality to copy a file in C#. File.Copy method copies an existing file to a new file on the specified location.
 
File.Copy method takes three parameters. First the original file with full path, second the file to be copied file name with the new path and third parameter that is optional that is used to overwrite an existing file. If third parameter is true, the Copy method will overwrite if file already exists.
 
The following code snippet copies the source file to the destination file. 
  1. string sourceFile = @"C:\Temp\MaheshTX.txt";  
  2. string destinationFile = @"C:\Temp\Data\MaheshTXCopied.txt";  
  3. try  
  4. {  
  5. File.Copy(sourceFile, destinationFile, true);  
  6. }  
  7. catch (IOException iox)  
  8. {  
  9. Console.WriteLine(iox.Message);  
  10. }  
 
Alternatively, we can also use a FileInfo class's CopyTo or MoveTo method. Learn more here on Working with FileInfo Class In C#.