C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: We invoke File.Replace. It accepts 3 arguments: the source file name, the destination file name, and the backup file name.
C# program that uses File.Replace method
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");
}
}
Output
test1.txt: test2
test3.txt: test1
And: The other two files passed as arguments to File.Replace are retained or created on the disk.
Therefore: Instead of implementing your own Replace methods, you can use this abstraction to handle possible errors.