C# copy file
last modified January 21, 2024
In this article we show how to copy files in C#. The File.Copy
method copies an existing file to a new file. The method is available in the
System.IO
namespace.
C# Copy.File synopsis
public static void Copy(string sourceFileName, string destFileName);
The first argument of the method is the source file; the second argument is the destination file.
public static void Copy(string sourceFileName, string destFileName, bool overwrite);
The overloaded method takes a third argument: overwrite
. It is a
boolean value which tells if the destination file can be overwritten.
C# copy file example
The following example copies a file on a disk.
var source = @"C:\Users\Jano\Documents\words.txt"; var destination = @"C:\Users\Jano\Documents\words_bck.txt"; File.Copy(source, destination); Console.WriteLine("File copied");
The example copies a text file.
var source = @"C:\Users\Jano\Documents\words.txt"; var destination = @"C:\Users\Jano\Documents\words_bck.txt";
We define a source and destination files.
File.Copy(source, destination);
The file is copied with the File.Copy
method.
$ dotnet run File copied $ dotnet run Unhandled exception. System.IO.IOException: The file 'C:\Users\Jano\Documents\words_bck.txt' already exists. ...
If we run the example twice, we have an exception telling us that the file
already exists. If we use the overloaded method and set the third parameter to
true
, the destination file will be overwritten.
C# copy files example
In the following example, we copy multiple files.
string sourceDir = @"C:\Users\Jano\Documents\"; string backupDir = @"C:\Users\Jano\Documents\backup\"; string[] textFiles = Directory.GetFiles(sourceDir, "*.txt"); foreach (string textFile in textFiles) { string fileName = textFile.Substring(sourceDir.Length); File.Copy(Path.Combine(sourceDir, fileName), Path.Combine(backupDir, fileName), true); } Console.WriteLine("Files copied");
The example copies all text files to a backup directory.
string[] textFiles = Directory.GetFiles(sourceDir, "*.txt");
We enumerate all text files in the source directory.
foreach (string textFile in textFiles) { string fileName = textFile.Substring(sourceDir.Length); File.Copy(Path.Combine(sourceDir, fileName), Path.Combine(backupDir, fileName), true); }
In a foreach
loop, we go through the list of text files and copy
them. We cut the file name from the absolute path using the
Substring
method. The Path.Combine
combines strings
into a path.
Source
In this article we have copied files in C#.
Author
List all C# tutorials.