Using a StreamReader

To create a character-based input stream, wrap a byte stream inside a StreamReader. StreamReader defines several constructors. A frequently used one is shown here:
StreamReader(Stream stream)
Here, stream is the name of an open stream. This constructor throws an ArgumentNullException if stream is null. It throws an ArgumentException if stream
is not opened for input. Once created, a StreamReader will automatically handle the conversion of bytes to characters. When you are done with the StreamReader, you must close it. Closing the StreamReader also closes the underlying stream.
 
The following program creates a simple disk-to-screen utility that reads a text file called test.txt and displays its contents on the screen.

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class DtoS
    {
        static void Main()
        {
            FileStream fin;
            string s;
            try
            {
                fin = new FileStream("test.txt", FileMode.Open);
            }
            catch (IOException exc)
            {
                Console.WriteLine("Error Opening file:\n" + exc.Message);
                return;
            }
            StreamReader fstr_in = new StreamReader(fin);
            try
            {
                while ((s = fstr_in.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
            catch (IOException exc)
            {
                Console.WriteLine("I/O Error:\n" + exc.Message);
            }
            finally
            {
                fstr_in.Close();
            }

        }
    }
}

In the program, notice how the end of the file is determined. When the reference returned by ReadLine( ) is null, the end of the file has been reached. Although this approach works, StreamReader provides an alternative means of detecting the end of the stream: the EndOfStream property. This read-only property is true when the end of the stream has been reached and false otherwise. Therefore, you can use EndOfStream to watch for the end of a file. For example, here is another way to write the while loop that reads the file:

while (!fstr_in.EndOfStream)
{
    s = fstr_in.ReadLine();
    Console.WriteLine(s);
}