.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda LINQ Parse Path Process Property Regex Replace Sort Split Static StringBuilder Substring Switch Tuple


C#:File

File.Copy copies a file from one location to another. It leaves both copies on the disk. It is part of the System.IO namespace. We break down three common uses of File.Copy. We warn of potential errors.


Example. Here we want to copy one file to a new location, one where no file exists. This is straightforward and you will see that both files in the example, file-a.txt and file-new.txt, have the same contents.

Next: This program takes a file that exists, file-a.txt, and copies it to file-new.txt. Both files contain the same string.

And: It displays the contents of both files, using Console.WriteLine and File.ReadAllText, to prove equality.

Console.WriteLine
C# program that uses File.Copy

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"));
    }
}

Output

Contents of File A.
Contents of File A.

Example 2. We find that File.Copy will cause an exception if you use it when the target destination already has a file there. To solve this problem, you must specify the third parameter of File.Copy to be true.

C# program that uses File.Copy parameters

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"));
    }
}

Output

"Contents of File A."
"Contents of File A."

First the example displays the contents of file-b.txt. Then it calls File.Copy and copies file-a.txt to file-b.txt. No exception is thrown here. It finally displays the contents of the two files, which are now equal.


Example 3. File.Copy will throw FileNotFoundException and IOException if there are certain problems. It will also throw other exceptions that I do not show here. You will find them annoying enough without my help.

FileNotFoundExceptionIOException
C# program that demonstrates File.Copy exceptions

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.
	}
    }
}

The program has two try-catch blocks. The first one protects the program from a call to File.Copy that tries to copy a missing file. It demonstrates that the FileNotFoundException is thrown.

TryCatch

Next, the second try-catch block demonstrates that the IOException is thrown when you try to copy to a file that exists, but don't specify overwrite. To specify overwrite, use true as the third parameter.

True, False

Caution: File IO will occasionally throw exceptions. It is one of the best uses for exception-handling.

Tip: You should wrap your File.Copy, as well as other methods such as File.ReadAllText, inside a try-catch block.

File.ReadAllText

Discussion. The File.Replace combine File.Copy with a deletion of the file. You can duplicate its functionality with File.Copy and then File.Delete. File.Move does a file system rename instead of copying any data.

File.Move

Also: More information on exceptions caused by File.Copy and other methods in System.IO is available.

Exception

Summary. Here we saw two useful ways to use File.Copy in the C# language, and saw examples of two ways it can throw exceptions. It is important that you handle errors when using File.Copy, or it may bring down your program.