Text files provide the users and programmers easy way to read and understand the data. In .NET Framework there are some classes which make some operation regarding to the text files like reading and writing to the Text Files. These are the following steps which outlines how to work with text files.

  1. Open the text file.
  2. Read/Write the text files.
  3. Close the text files.

First we will see how to write to a Text File. Let's have a look on the following example

using System;
using System.IO;

using System.Text;

namespace txtfile
{
    class filewrite
    {
        static void Main(string[] args)
        {
            // create a writer and open the file
            TextWriter tw1 = new StreamWriter("myfile.txt");

            // write a line of text to the file
            tw1.WriteLine("my first file");
            tw2.WriteLine("my second file");
            tw3.WriteLine("My third file");

            // close the stream
            tw1.Close();
        }

    }
}


When we will run this program this will create a text file named "myfile.txt" and if we will see view this file then we will see the following textual representation of the following data.

my first file
my second file
my third file

This is possible to write the text in the text file by using TextWriter Class instance.

Reading From a text File.

We can also read data from the existing Text File. For this we need to use Textreader class in C# and also we will use the StreamReader class constructor to create instance of a TextReader.

Lets have a look on the following example to see how to read text from the Textfile.

using System;
using System.IO;
namespace csharp_station.howto
{
    class
 txtfileread
    {
        static
 void Main(string[] args)
        {
            // create reader & open file

            Textreader tr1 = new StreamReader("myfile.txt");
            // read a line of text
            Console.WriteLine(tr1.ReadLine());
            // close the stream
            tr1.Close();
        }
    }
}


Here when reading of the file will be completed then it should be closed to open it in different reading mode. So to close it we will call the close method like this:

tr1.Close();

Next Recommended Readings