Example. 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.
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.
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.
Example 2. 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.
Tip To solve this problem, you must specify the third parameter of File.Copy to be true. This will avoid the exception.
Here The example displays the contents of file-b.txt. Then it calls File.Copy and copies file-a.txt to file-b.txt.
Detail No exception is thrown here. The code displays the contents of the two files, which are now equal.
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."
Example 3. File.Copy will throw FileNotFoundException and IOException if there are certain problems. These should be tested for in most programs.
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.
}
}
}
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 26, 2023 (edit).