C# - Read Text from a File and Append in Another File

Here, we will learn how can we read text from a file and append in another file using C# program?
Submitted by IncludeHelp, on October 28, 2017 [Last updated : March 23, 2023]

Reading and Appending Text to a File

To read and append text to a file, we use File.AppendAllText() function, which is a function of the File class. It accepts two parameters path and content.

Syntax:

void File.AppendAllText(path, content);

C# program to read text from a file and append in another 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 append:");
      s = File.ReadAllText("ABC.TXT");
      Console.WriteLine(s);

      Console.WriteLine("Enter text to append into file:");
      s = Console.ReadLine();

      File.AppendAllText("ABC.TXT", s);

      Console.WriteLine("Content after append:");
      s = File.ReadAllText("ABC.TXT");
      Console.WriteLine(s);

    }
  }
}

Output

Content of file :
Content before append:
Hello , This is a sample program for writing text into file.
Enter text to append into file:
It is new Text.
Content after append:
Hello , This is a sample program for writing text into file.It is new Text.

Explanation

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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.