Q:

C# program to replace content of one file from other file and create backup file

0

Given a file, and we have replace its text with the text of another file, also create a backup file using C# program.

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);

Parameters:

  1. source-file - Source file by which we replace destination file.
  2. dest-file - Destination file which will be replaced by source file.
  3. backup-file - It is the backup file of Destination file.
  4.  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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 above program, we need to remember, when we use "File" class, System.IO namespace must be included in the program.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# file handling (File class) solved programs/examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to delete a text file... >>
<< C# program to read text from a file and append in ...