Home
C#
File.Replace Method
Updated Oct 24, 2021
Dot Net Perls
File.Replace. A file needs to be replaced. With File.Replace, we replace the contents of one file with another. The original file is then deleted.
C# method notes. We could implement this logic with a series of file calls. But the File.Replace method is simpler. We can perform the task with a single call.
File
File.Copy
Example. This program uses the File.WriteAllText method to create 2 local text files. Because no absolute directory is specified, they are created in the directory local to the executable.
Next We invoke File.Replace. It accepts 3 arguments: the source file name, the destination file name, and the backup file name.
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"); } }
test1.txt: test2 test3.txt: test1
Output notes. The contents of test1.txt are now equal to the original contents of test2.txt. And test3.txt contains the contents of test1.txt.
Argument 1 The first argument to File.Replace is the file that will be deleted when the method completes.
Info The other two files passed as arguments to File.Replace are retained or created on the disk.
Summary. The File.Replace method provides a much-needed mechanism to automatically replace the contents of a file. Not only this, but it allows you to back up the original data.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 24, 2021 (rewrite).
Home
Changes
© 2007-2025 Sam Allen