C# CopyTo

Summary: in this tutorial, you’ll learn how to use the C# FileInfo CopyTo() to copy an existing file to a new file.

Introduction to the C# FileInfo CopyTo() method

The FileInfo.CopyTo() allows you to copy an existing file to a new file:

FileInfo CopyTo (string destFileName);Code language: C# (cs)

If the destFileName exists or an error occurs during the copying of the file, the CopyTo raises an IOException.

To overwrite the destination file, you use an overload of the CopyTo() method:

FileInfo CopyTo (string destFileName, bool overwrite);Code language: C# (cs)

When you set the overwrite argument to true, the CopyTo() method will overwrite the destination file if it exists. But if you set the overwrite to false, then the CopyTo() won’t overwrite the destination file.

The CopyTo() method returns a FileInfo object that has methods for common file operations such as copying, deletion, moving, and opening files.

Note that if you perform multiple operations on the same file, it is more efficient to use the FileInfo object than the static method of the File class.

C# FileInfo Copy() method example

The following example demonstrates how to use the FileInfo Copy() method to copy the readme.txt file from the C:\temp directory to the C:\backup directory and overwrite if the file exists:

using static System.Console;

string filename = @"C:\temp\readme.txt";

var file = new FileInfo(filename);

try
{
    file.CopyTo(
         Path.Combine(@"C:\backup", "readme.txt"),
         true
    );
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}
Code language: C# (cs)

How it works.

First, define a path to the file to copy:

string filename = @"C:\temp\readme.txt";Code language: C# (cs)

Second, create a new instance of FileInfo object:

var file = new FileInfo(filename);Code language: C# (cs)

Third, copy the file using the CopyTo() method of the FileInfo object:

try
{
    file.CopyTo(
         Path.Combine(@"C:\backup", "readme.txt"),
         true
    );
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}Code language: C# (cs)

Since the CopyTo() may raise an exception, we wrap it in a try...catch block.

Summary

  • Use the C# FileInfo CopyTo() to copy an existing file to a new file and overwrite it if the destination file exists.
Was this tutorial helpful ?