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