In this tutorial I will show you how to read files using Visual Studio 2008 C#.
The TextReader Class (from MSDN)
TextReader is the abstract base class of StreamReader and StringReader, which read characters from streams and strings, respectively. Use these derived classes to open a text file for reading a specified range of characters, or to create a reader based on an existing stream.
Getting Started
1) Open Visual Studio 2008 and create a new Console Application using Visual C#. I've named my project ccFileRead but you can name as you like. We will be using a Console Application in order to eliminate confusion with GUI objects. This tutorial is intended to show you how to read a file.

2) Click "Start/Run" and type "notepad", press enter. We will create a txt file to read in this step. Type in several names pressing enter after each name. I used Luke, John, Jerry, Winged, TcM, Jordan. This file is also attached at the bottom of this thread. Once you have entered the names click "File/Save As". Click "My Computer" on the left hand side of the Save As dialog. Double click "Local Disk (C:)". Type "UserNames.txt" as the "File Name:" in the bottom of the dialog. Click Save.

3) Close the text file and switch back to Visual Studio 2008. You should see the default Console Application code generated by C#.
[highlight="C#"]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ccFileRead
{
class Program
{
static void Main(string[] args)
{
}
}
}[/highlight]
Reading a Text File
The TextReader is in the System.IO namespace. The first thing you should do is add this line to the top of your program:
directly under:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Now you will be able to use the entire IO namespace without typing out the full name. Next we want to create a string and assign it the path/name of our file:
Code:
// Assign the filename
string fileName = "c:\\UserNames.txt";
Add this in the "static void Main(string[] args)" function (between the { and }). The double blackslash is required to assert a single backslash. This is because a single backslash key is defined as the escape character.
Creating the TextReader
The TextReader is defined by creating a new StreamReader and passing the file path/name to it. StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.
StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system.
Thus you have:
Code:
// Create reader & open file
TextReader textReader = new StreamReader(fileName);
Add this directly below the fileName string you set earlier.
Reading the File
Reading the file with a TextReader is incredibly simple. There are two methods for reading the file: ReadLine and ReadToEnd. As you may have guessed the ReadLine() method reads only one line. The ReadToEnd() reads the entire file. Since we have multiple names on different lines we need to use the ReadToEnd(). We also want to display this information to the user and print the TextReader Type (using the GetType().Name property). Add this line below the previous:
Code:
// Read text to end of file
Console.WriteLine("Reading {0} - {1}",
textReader.GetType().Name, textReader.ReadToEnd());
Closing the Stream
Once you are done using your file streams it is important to close them. This frees up the file and memory. Added:
Code:
// close the stream
textReader.Close();
Final Code
Your code should look like this:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ccFileRead
{
class Program
{
static void Main(string[] args)
{
// Assign the filename
string fileName = "c:\\UserNames.txt";
// Create reader & open file
TextReader textReader = new StreamReader(fileName);
// Read text to end of file
Console.WriteLine("Reading {0} - {1}",
textReader.GetType().Name, textReader.ReadToEnd());
// close the stream
textReader.Close();
}
}
}
Running the Code
Press F5 or click the Start Debugging (green arrow) button to build and execute your code. After your code compiles a black box (cmd prompt) appears and executes your code. Then exits before you can see the console. In order to fix this lets add a pause.
Last Minute Changes
Below "textReader.Close();" we need to pause the problem so that the output can be observed. The easiest way to do this is to accept user input. Once the user presses enter (or any other key) the code will continue to run. Add:
Code:
// Accept User Input
Console.Read();
Your code should now look similar to this:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ccFileRead
{
class Program
{
static void Main(string[] args)
{
// Assign the filename
string fileName = "c:\\UserNames.txt";
// Create reader & open file
TextReader textReader = new StreamReader(fileName);
// Read text to end of file
Console.WriteLine("Reading {0} - {1}",
textReader.GetType().Name, textReader.ReadToEnd());
// close the stream
textReader.Close();
// Accept User Input
Console.Read();
}
}
}
Build and Execute your program (F5 or Green Arrow).
Final Output
Your program now reads the text file you create, lists the TextRead type and displays all of the user names pausing at the end to allow user input.

If you have any questions or comments please post them here.
Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum