How to Copy a File in C#: Simple Guide with Examples
In C#, you can copy a file using the
File.Copy method from the System.IO namespace. This method requires the source file path and the destination file path, and optionally allows overwriting an existing file.Syntax
The File.Copy method copies an existing file to a new file. It has two main forms:
File.Copy(string sourceFileName, string destFileName): Copies the file without overwriting if the destination exists.File.Copy(string sourceFileName, string destFileName, bool overwrite): Copies the file and overwrites the destination ifoverwriteistrue.
Parameters:
- sourceFileName: Path of the file to copy.
- destFileName: Path where the file will be copied.
- overwrite (optional): Whether to overwrite the destination file if it exists.
csharp
File.Copy(string sourceFileName, string destFileName); File.Copy(string sourceFileName, string destFileName, bool overwrite);
Example
This example copies a file named example.txt from the current folder to copy_example.txt. It overwrites the destination if it already exists.
csharp
using System; using System.IO; class Program { static void Main() { string sourcePath = "example.txt"; string destinationPath = "copy_example.txt"; try { File.Copy(sourcePath, destinationPath, true); Console.WriteLine($"File copied from '{sourcePath}' to '{destinationPath}'."); } catch (Exception ex) { Console.WriteLine($"Error copying file: {ex.Message}"); } } }
Output
File copied from 'example.txt' to 'copy_example.txt'.
Common Pitfalls
Common mistakes when copying files in C# include:
- Not handling exceptions like
FileNotFoundExceptionorUnauthorizedAccessException. - Trying to copy to a destination file that already exists without setting
overwritetotrue, which causes anIOException. - Using incorrect file paths or missing file extensions.
Always use try-catch blocks to handle errors gracefully.
csharp
/* Wrong way: This throws IOException if destination exists */ File.Copy("source.txt", "dest.txt"); /* Right way: Overwrite if destination exists */ File.Copy("source.txt", "dest.txt", true);
Quick Reference
| Method | Description |
|---|---|
| File.Copy(source, dest) | Copies file; throws error if dest exists |
| File.Copy(source, dest, true) | Copies file and overwrites if dest exists |
| Try-catch block | Use to handle errors like missing files or access issues |
Key Takeaways
Use System.IO.File.Copy to copy files in C#.
Set the overwrite parameter to true to replace existing files.
Always handle exceptions to avoid runtime errors.
Provide correct full or relative file paths.
Use try-catch blocks to manage file access issues gracefully.