
Sometimes you will want to replace the contents of one file with another file, and then delete the original file. And although you can implement this logic with a series of file calls, the File.Replace method in the C# language provides a usable way to do this automatically.
This C# article tests the File.Replace method in the System.IO namespace.
To start, we create a program that uses the File.WriteAllText method to create two local text files. Because no absolute directory is specified, they are created in the directory local to the executable. Next, we invoke the File.Replace method, which accepts three arguments: the source file name, the destination file name, and the backup file name.
Program that uses File.Replace method [C#]
using System.IO;
class Program
{
static void Main()
{
// Write to local file 1.
File.WriteAllText("test1.txt", "test1");
// Write to local file 2.
File.WriteAllText("test2.txt", "test2");
// Replace contents of file 1 with contents of file 2.
// ... Also create file 3 as backup.
File.Replace("test2.txt", "test1.txt", "test3.txt");
}
}
Result
test1.txt: test2
test3.txt: test1
Results. The results section of the example shows that the contents of test1.txt are now equal to the original contents of test2.txt. Also, the file test3.txt contains the original contents of test1.txt. The first argument to the File.Replace method indicates the file that will be deleted when the method completes; the other two files are retained or created on the disk.

The File.Replace method provides a much-needed mechanism to automatically replace the contents of one file with another. Not only this, but it allows you to back up the original data. Therefore, instead of implementing your own Replace methods through combinations of more primitive file method invocations, you can tap this abstraction to handle possible errors with a lower cognitive burden.
File Handling