In this tutorial, we will learn how to use the System.IO namespace and the provided methods to copy the files.
Method 1: Using the File.Copy Method
The first and most common method of copying a file is using the File.Copy() method from the System.IO namespace.
This method copies an existing file to a new file. The method syntax is as follows:
The method accepts two main parameters:
- sourceFileName – This specifies the path to the file that we wish to copy.
- destFileName – This specifies the path to the destination file. The provided path cannot be a directory or an existing filename.
The following example demonstrates how to use the Copy() method to copy a file in C#:
using System.IO;
class Program
{
static void Main()
{
string sourceFile = @"C:\sample\linuxhint\sample.zip";
string destinationFile = @"C:\sample\linuxhint\compress.zip";
File.Copy(sourceFile, destinationFile);
Console.WriteLine($"copied from {sourceFile} to {destinationFile}");
}
}
Output:
Overwriting an Existing File
The Copy() method also allows us to override an existing file by setting the third parameter to “true” as shown in the following syntax:
Setting the overwrite parameter to “true” ensures that we overwrite an existing file.
using System.IO;
class Program
{
static void Main()
{
string sourceFile = @"C:\sample\linuxhint\sample.zip ";
string destinationFile = @"C:\sample\linuxhint\existing.zip";
File.Copy(sourceFile, destinationFile, true);
Console.WriteLine($"File copied from {sourceFile} to {destinationFile}");
}
}
You might notice that we set the overwrite parameter to “true” in this example.
Method 2: Using the FileInfo.CopyTo Method
We also have the CopyTo method from the “FileInfo” class which allows us to copy a file from one source to another.
The syntax is as follows:
The method accepts the name of the new file in which we wish to copy.
It then returns the FQP or Fully Qualified Path of the new file. An example code is as follows:
using System.IO;
class Program
{
static void Main()
{
string sourceFile = @"C:\sample\linuxhint\sample.zip";
string destinationFile = @"C:\sample\linuxhint\compress.zip";
FileInfo fileInfo = new FileInfo(sourceFile);
fileInfo.CopyTo(destinationFile);
}
}
This should copy the file source to the destination.
Conclusion
In this tutorial, we covered two main methods that we can use to copy a file from a source to a given destination.