This post will discuss how to copy a file to another location in C#.

1. Using File.Copy() method

You can use File.Copy(src, dest) method to copy an existing file to a new file, which can have a different file name than the source file. The File class is available from the System.IO namespace, and both src and dest can be relative or absolute paths.

The following example copies the file specified by src to the file specified by dest using the File.Copy() method.

Download Code

 
You should enclose your code within a try-catch block, and ensure that the path specified by src and dest is valid before invoking the File.Copy() method.

Download Code

 
The above version of File.Copy() does not allow overwriting files that already exist, and throws System.IO.IOException. The File.Copy() method can accept an optional boolean parameter which, if true, will overwrite the target file.

Download Code

2. Using FileInfo.CopyTo() method

Alternatively, you can use the FileInfo.CopyTo() method to copy an existing file to a new location. The default behavior of this method does not allow overwriting of an existing file.

Download Code

 
To override an existing file, you can invoke the CopyTo(String, Boolean) overload, which accepts a boolean overwrite parameter. If the overwrite parameter is true, the existing file will be overwritten.

Download Code

That’s all about copying a file to another location in C#.