File.Copy
This .NET method copies a file from one location to another. It leaves both copies on the disk. It is part of the System.IO
namespace.
We demonstrate 3 common uses of File.Copy
. We warn of potential errors. Exception
handling often should be used when File.Copy
is invoked.
Here we want to copy one file to a new location, one where no file exists. Both files in the example, file-a.txt and file-new.txt, have the same contents.
string
.Console.WriteLine
and File.ReadAllText
, to prove equality.using System; using System.IO; class Program { static void Main() { // Copy one file to a nonexistent location File.Copy("file-a.txt", "file-new.txt"); // Display the contents of both files Console.WriteLine(File.ReadAllText("file-a.txt")); Console.WriteLine(File.ReadAllText("file-new.txt")); } }Contents of File A. Contents of File A.
File.Copy
will cause an exception if you use it when the target destination already has a file there. It will not write over an existing file.
File.Copy
to be true. This will avoid the exception.File.Copy
and copies file-a.txt to file-b.txt.using System; using System.IO; class Program { static void Main() { // Write initial contents of File B. Console.WriteLine(File.ReadAllText("file-b.txt")); // "File B contents." // COPY: // Copy one file to a location where there is a file. File.Copy("file-a.txt", "file-b.txt", true); // overwrite = true // Display the contents of both files Console.WriteLine(File.ReadAllText("file-a.txt")); Console.WriteLine(File.ReadAllText("file-b.txt")); } }"Contents of File A." "Contents of File A."
File.Copy
will throw FileNotFoundException
and IOException
if there are certain problems. These should be tested for in most programs.
try-catch
blocks. It uses File.Copy
to copy a missing file. The FileNotFoundException
is thrown.IOException
when we copy to a file that exists, but don't specify overwrite. For overwrite, use true as the third parameter.File.Copy
, as well as other methods such as File.ReadAllText
, inside a try-catch
block.using System; using System.IO; class Program { static void Main() { // Copying a file that doesn't exist: try { File.Copy("file-missing.txt", "file-new.txt"); } catch (Exception ex) { Console.WriteLine(ex); // System.IO.FileNotFoundException: Could not find file 'file-missing.txt'. } // Copying to a file without overwrite try { File.Copy("file-a.txt", "file-b.txt"); } catch (Exception ex) { Console.WriteLine(ex); // System.IO.IOException: The file 'file-b.txt' already exists. } } }
We saw several ways to use File.Copy
. We reviewed the exceptions caused by this C# method. It is important that you handle errors when using File.Copy
.