Home »
.Net »
C# Programs
C# - Replace Content of One File with Another, Create Backup File
Learn, how to replace text of a file with the text of another file and also create a backup file?
Submitted by IncludeHelp, on October 28, 2017 [Last updated : March 26, 2023]
Given a file, and we have replace its text with the text of another file, also create a backup file using C# program.
To replace content of one file with another and create backup file, we use File.Replace() method.
File.Replace()
This is a method of "File" class, it is used to replace 'source-file' with the 'dest-file' by keeping a backup in 'backup-file'.
Syntax
File.Replace(source-file, dest-file, backup-file);
Parameter(s)
- source-file - Source file by which we replace destination file.
- dest-file - Destination file which will be replaced by source file.
- backup-file - It is the backup file of Destination file.
C# program to replace content of one file with another and create backup file
using System;
// We need to include this namespace
// for file handling
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main() {
string s;
Console.WriteLine("Content Before Replace:\n\n");
Console.WriteLine("Content of File(ABC.TXT):");
s = File.ReadAllText("ABC.TXT");
Console.WriteLine(s);
Console.WriteLine("Content of File(123.TXT):");
s = File.ReadAllText("123.TXT");
Console.WriteLine(s);
File.Replace("ABC.TXT", "123.TXT", "XYZ.TXT");
Console.WriteLine("\n\nContent After Replace:\n\n");
Console.WriteLine("Content of File(123.TXT):");
s = File.ReadAllText("123.TXT");
Console.WriteLine(s);
Console.WriteLine("Content of File(XYZ.TXT):");
s = File.ReadAllText("XYZ.TXT");
Console.WriteLine(s);
}
}
}
Output
Content Before Replace:
Content of File(ABC.TXT):
Mahenda Singh Dhoni is a greatest captain of indian cricket team.
Content of File(123.TXT):
Hello , This is a sample program for writing text into file.It is new Text.
Content After Replace:
Content of File(123.TXT):
Mahenda Singh Dhoni is a greatest captain of indian cricket team.
Content of File(XYZ.TXT):
Hello , This is a sample program for writing text into file.It is new Text.
Note
In the above program, we need to remember, when we use "File" class, System.IO namespace must be included in the program.
C# File Handling Programs »