How do you copy a file from one location to another in C#?
How do you copy a file from one location to another in C#? ICSM Computer 580 05 May 2025 How do you copy a file from one location to another in C#?
In C#, you can copy a file from one location to another using the
File.Copymethod from theSystem.IOnamespace.Syntax:
sourceFileName: Full path to the file you want to copy.destFileName: Full path where you want the file copied.overwrite(optional): Set totrueif you want to overwrite the destination file if it exists.Example 1: Copy without overwrite
This throws an exception if the destination file already exists.
Example 2: Copy with overwrite
This replaces the destination file if it already exists.
Exceptions to handle (optionally):
FileNotFoundException: If the source file doesn't exist.IOException: If the destination file exists andoverwriteisfalse.UnauthorizedAccessException: If access is denied (e.g., permissions).DirectoryNotFoundException: If the path is invalid.