Visual C# Guide
Reading Text Files

A basic definition of a text file is that it is a sequence of printable characters organised on a line-by-line basis. The end of each line usually has a termination marker such as a semi-colon or a carriage return.

The following program reads from a small text file, get the file by clicking here with the right mouse button and saving it. There are 6 lines in the file, a question, 4 possible answers and the correct answer.

You will need to add the following statement to the using section at the top of the code window,

using System.IO;

You will also need to adjust the path to the file specified in the program so that your version of the program can locate it.

Read All Text

This is the easiest way to get the entire contents of a text file. Unfortunately, you are unlikely to need to use this method. The first line includes a @ because the backslash in the path string is usually used as an escape character (but that isn't what we want to do here). A search in the MSDN for escape characters will give you all of the information that you need.

string path = @"C:\questions.txt";
string fileText = File.ReadAllText(path);

Reading A Line At A Time

More often than not, you will want to process information from the file as it being read. At the very least, you are likely to want to store the information in variables or structures that you have set up for the purpose.

string path = @"C:\questions.txt";
string lineOfText;
StreamReader sr = new StreamReader(path);
while (!sr.EndOfStream)
   lineOfText = sr.ReadLine();

This program produces the same output as the first but allows you to work with a line at a time.

Notice that we close the stream at the end of processing.

Having A Go

  1. Write a program that reads a text file and counts the number of lines, words and characters.