C# copy file
last modified November 6, 2026
In this article we show how to copy files and directories in C#.
The File.Copy method from the System.IO namespace
copies a file to a new location. It has two overloads:
public static void Copy(string sourceFileName, string destFileName); public static void Copy(string sourceFileName, string destFileName, bool overwrite);
The first throws an IOException if the destination exists; the
second replaces it when overwrite is true. The
FileInfo.CopyTo method does the same for a FileInfo
object. There is no built-in method for copying a directory.
The examples create the files they copy and delete them at the end.
Copying a file
The first example copies a file, fails to copy it again, and then overwrites the copy.
File.WriteAllText("words.txt", "sky\nblue\nforest\n");
File.Copy("words.txt", "words_bck.txt");
Console.WriteLine($"Copied: {File.ReadAllText("words_bck.txt").Length} chars");
try
{
File.Copy("words.txt", "words_bck.txt");
}
catch (IOException e)
{
Console.WriteLine($"{e.GetType().Name}: {e.Message.Replace(Environment.CurrentDirectory, ".")}");
}
File.WriteAllText("words.txt", "new content\n");
File.Copy("words.txt", "words_bck.txt", overwrite: true);
Console.Write($"After overwrite: {File.ReadAllText("words_bck.txt")}");
File.Delete("words.txt");
File.Delete("words_bck.txt");
The destination path includes the new file name. A directory alone is not accepted.
File.Copy("words.txt", "words_bck.txt");
The second call with the same destination throws an
IOException, because the copy already exists. We shorten the
absolute path in the message to ..
File.Copy("words.txt", "words_bck.txt", overwrite: true);
With overwrite: true, the existing copy is replaced with the new
content.
$ dotnet run Copied: 16 chars IOException: The file './words_bck.txt' already exists. After overwrite: new content
Copying several files
To back up a group of files, we list them with Directory.GetFiles
and copy them one by one.
Directory.CreateDirectory("demo");
File.WriteAllText("demo/a.txt", "a");
File.WriteAllText("demo/b.txt", "b");
File.WriteAllText("demo/c.csv", "c");
string backupDir = Path.Combine("demo", "backup");
Directory.CreateDirectory(backupDir);
foreach (string file in Directory.GetFiles("demo", "*.txt").Order())
{
string target = Path.Combine(backupDir, Path.GetFileName(file));
File.Copy(file, target, overwrite: true);
Console.WriteLine($"{file} -> {target}");
}
Directory.Delete("demo", recursive: true);
The demo directory has two text files and one CSV file.
Directory.CreateDirectory(backupDir);
File.Copy does not create missing directories, so we create the
backup directory first. The call does nothing if it already exists.
string target = Path.Combine(backupDir, Path.GetFileName(file));
GetFiles returns paths that include the directory.
Path.GetFileName takes the file name from the path and
Path.Combine joins it with the backup directory. The order of
GetFiles is not defined, so we sort the paths.
$ dotnet run demo/a.txt -> demo/backup/a.txt demo/b.txt -> demo/backup/b.txt
Handling errors
A copy can fail for several reasons. The exception type tells which.
File.WriteAllText("data.txt", "data");
Copy("missing.txt", "copy.txt");
Copy("data.txt", Path.Combine("nodir", "copy.txt"));
Copy("data.txt", "copy.txt");
Copy("data.txt", "copy.txt");
File.Delete("data.txt");
File.Delete("copy.txt");
static void Copy(string source, string destination)
{
try
{
File.Copy(source, destination);
Console.WriteLine($"{source} copied to {destination}");
}
catch (FileNotFoundException e)
{
Console.WriteLine($"Source not found: {Path.GetFileName(e.FileName)}");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"Destination directory does not exist: {destination}");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Permission denied");
}
catch (IOException) when (File.Exists(destination))
{
Console.WriteLine($"Destination already exists: {destination}");
}
}
We try four copies: from a missing file, into a missing directory, a normal copy, and the same copy again.
catch (FileNotFoundException e)
FileNotFoundException and DirectoryNotFoundException
derive from IOException, so they must be caught before it. The
FileName property holds the missing source path.
catch (UnauthorizedAccessException)
A missing permission throws UnauthorizedAccessException, which is
not an IOException.
catch (IOException) when (File.Exists(destination))
An existing destination throws a plain IOException. The
exception filter catches it only when the destination exists; other I/O errors,
such as a full disk, propagate.
$ dotnet run Source not found: missing.txt Destination directory does not exist: nodir/copy.txt data.txt copied to copy.txt Destination already exists: copy.txt
Copying with progress
File.Copy gives no progress information. For long copies, we can
copy the data ourselves with streams.
var data = new byte[10_000_000];
Random.Shared.NextBytes(data);
File.WriteAllBytes("large.dat", data);
CopyWithProgress("large.dat", "large_copy.dat", p => Console.WriteLine($"{p,3}%"));
Console.WriteLine($"Identical: {File.ReadAllBytes("large_copy.dat").AsSpan().SequenceEqual(data)}");
File.Delete("large.dat");
File.Delete("large_copy.dat");
static void CopyWithProgress(string source, string destination, Action<int> report)
{
using var input = File.OpenRead(source);
using var output = File.Create(destination);
var buffer = new byte[81920];
long total = input.Length;
long copied = 0;
int lastReported = -1;
int n;
while ((n = input.Read(buffer)) > 0)
{
output.Write(buffer, 0, n);
copied += n;
int percent = (int) (copied * 100 / total);
if (percent / 25 != lastReported / 25)
{
report(percent);
lastReported = percent;
}
}
}
We create a 10 MB file of random bytes and copy it in 80 KB blocks.
while ((n = input.Read(buffer)) > 0)
{
output.Write(buffer, 0, n);
Read returns the number of bytes read, which can be less than the
buffer size. Only that many bytes are written.
if (percent / 25 != lastReported / 25)
We report progress only when it crosses a 25% step, instead of after every block. The callback lets the caller decide how to display it.
$ dotnet run 25% 50% 75% 100% Identical: True
Copying a directory
A directory tree is copied with a recursive method: copy the files of the directory, then copy each subdirectory the same way.
Directory.CreateDirectory("project/src/utils");
Directory.CreateDirectory("project/docs");
File.WriteAllText("project/README.md", "readme");
File.WriteAllText("project/src/main.cs", "main");
File.WriteAllText("project/src/utils/strings.cs", "strings");
File.WriteAllText("project/docs/guide.md", "guide");
int count = CopyDirectory("project", "project_backup");
Console.WriteLine($"{count} files copied");
foreach (var file in Directory.EnumerateFiles("project_backup", "*", SearchOption.AllDirectories).Order())
{
Console.WriteLine(file);
}
Directory.Delete("project", true);
Directory.Delete("project_backup", true);
static int CopyDirectory(string source, string destination)
{
Directory.CreateDirectory(destination);
int count = 0;
foreach (var file in Directory.GetFiles(source))
{
File.Copy(file, Path.Combine(destination, Path.GetFileName(file)), true);
count++;
}
foreach (var dir in Directory.GetDirectories(source))
{
count += CopyDirectory(dir, Path.Combine(destination, Path.GetFileName(dir)));
}
return count;
}
We create a small project tree and copy it to project_backup.
count += CopyDirectory(dir, Path.Combine(destination, Path.GetFileName(dir)));
For a subdirectory, Path.GetFileName returns its last path
segment. The method calls itself and adds the number of files copied below.
$ dotnet run 4 files copied project_backup/docs/guide.md project_backup/README.md project_backup/src/main.cs project_backup/src/utils/strings.cs
Preserving metadata
File.Copy uses the copy function of the operating system, which
keeps the modification time and, on Unix, the permission bits. A copy made with
streams is a new file.
File.WriteAllText("report.txt", "quarterly report");
File.SetLastWriteTime("report.txt", new DateTime(2024, 3, 15, 10, 30, 0));
File.Copy("report.txt", "copy1.txt");
using (var input = File.OpenRead("report.txt"))
using (var output = File.Create("copy2.txt"))
{
input.CopyTo(output);
}
foreach (var name in new[] { "report.txt", "copy1.txt", "copy2.txt" })
{
var modified = File.GetLastWriteTime(name);
Console.WriteLine($"{name,-11} {(modified.Year == 2024 ? modified.ToString("yyyy-MM-dd HH:mm") : "now")}");
}
File.Delete("report.txt");
File.Delete("copy1.txt");
File.Delete("copy2.txt");
We set an old modification time on the source and copy it in both ways.
input.CopyTo(output);
Stream.CopyTo copies the content. The new file gets the current
time, which we print as now. To keep the time, call
File.SetLastWriteTime after the copy.
$ dotnet run report.txt 2024-03-15 10:30 copy1.txt 2024-03-15 10:30 copy2.txt now
Copying asynchronously
CopyToAsync copies a stream without blocking the calling thread.
var data = new byte[50_000_000];
Random.Shared.NextBytes(data);
await File.WriteAllBytesAsync("big.dat", data);
using var cts = new CancellationTokenSource();
Task copy = CopyFileAsync("big.dat", "big_copy.dat", cts.Token);
Console.WriteLine("Copy started, the main thread is free");
await copy;
Console.WriteLine($"Copied {new FileInfo("big_copy.dat").Length:N0} bytes");
File.Delete("big.dat");
File.Delete("big_copy.dat");
static async Task CopyFileAsync(string source, string destination, CancellationToken token)
{
var options = new FileStreamOptions { Options = FileOptions.Asynchronous };
await using var input = new FileStream(source, options);
await using var output = new FileStream(destination,
new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write,
Options = FileOptions.Asynchronous });
await input.CopyToAsync(output, token);
}
We copy a 50 MB file. The method returns a task immediately, and we can do other work before awaiting it.
var options = new FileStreamOptions { Options = FileOptions.Asynchronous };
FileOptions.Asynchronous opens the files for asynchronous I/O.
On Windows, this enables overlapped I/O; without it, the asynchronous methods
run synchronous reads and writes on a thread pool thread. On Linux and macOS,
.NET always uses the thread pool for file I/O. The default mode of
FileStreamOptions is FileMode.Open with read
access.
await input.CopyToAsync(output, token);
The cancellation token lets the caller stop a long copy.
$ dotnet run Copy started, the main thread is free Copied 50,000,000 bytes
Source
In this article we have copied files and directories in C#, handled copy errors, reported progress, and copied asynchronously.
Author
List all C# tutorials.