Reading and Writing Text File using C#.Net

This C# code snippet writes a text file from an internal string then reads it back using StreamReader, StreamWriter, TextReader, and TextWriter.

INTRODUCTION:


Here you can information about how to read or write (Unicode) character based data through TextReader and TextWriter.

The TextReader and TextWriter are base classes.

The StreamReader and StringReader derives from the abstract type TextReader. Similarly the StreamWriter and StringWriter derives from the abstract type TextWriter.

WRITING - TEXT FILE:

StreamWriter type derives from a base class named TextWriter. This class defines members that allow derived types to write textual data to a given character stream.

Let us see some of the main members of the abstract class TextWriter.

  • close() -- Closes the Writer and frees any associated resources.
  • Write() -- Writes a line to the text stream, with out a newline.
  • WriteLine() -- Writes a line to the text stream, with a newline.
  • Flush() -- Clears all buffers.

READING - TEXT FILE:

StreamReader type derives from a base class named TextReader.

Let us see some of the main members of the abstract class TextReader.

  • Read() -- Reads data from an input stream.
  • ReadLine() -- Reads a line of characters from the current stream and returns the data as a string.
  • ReadToEnd() -- Reads all characters to the end of the TextReader and returns them as one string.

C# Code

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

  

using System.IO;

  

public partial class ReadWriteFile : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

    protected void btnReadFile_Click(object sender, EventArgs e)

    {

        //Reading from File1

  

        TextReader tr = new StreamReader(Server.MapPath("File-1.txt"));

        Label1.Text = tr.ReadLine();

        Label1.Text += tr.ReadToEnd();

        tr.Close();

    }

    protected void btnWriteFile_Click(object sender, EventArgs e)

    {

        //Writing into File2

  

        TextWriter tw = new StreamWriter(Server.MapPath("File-2.txt"));

        tw.WriteLine("Cherukuri Venkateswarlu");

        tw.Close();

    }

}

I hope after reading this article, you might gain some information about how write and read in a text file using TextReader and TextWriter in C#.Net .