C# StreamReader

Stream abstract type

StreamReader reads text files. It is found in the System.IO namespace. It provides good performance and is easy to add to programs. It is often used with the using statement. This construct helps dispose of the system resources.

Example

We first use the StreamReader type inside a using-statement. This statement allows you to leave the file disposal and opening routines to the C# compiler's knowledge of scope. It makes the StreamReader much easier to use.

Using keyword

Using:This statement will be compiled to instructions that tell the runtime to do all the cleanup works on the Windows file handles.

Using
Based on:

.NET 4.5

Program that uses StreamReader: C#

using System;
using System.IO;

class Program
{
    static void Main()
    {
	//
	// It will free resources on its own.
	//
	string line;
	using (StreamReader reader = new StreamReader("file.txt"))
	{
	    line = reader.ReadLine();
	}
	Console.WriteLine(line);
    }
}

Output

First line of your file.txt file.
Logo

Scope is important. When objects go out of scope, the garbage collector or finalization code is run and your program's memory is reclaimed. Recall that a scope in your C# code is a block between brackets.

Tip:Scope allows the compiler to make many assumptions about your program. It can tell where the object becomes unreachable.

Next, we see an alternate syntax form for the inner-loop in the StreamReader. After years of using C#, I started preferring this syntax instead. It uses an if-statement with a break in it.

If
Code that uses while-true loop: C#

while (true)
{
    string line = reader.ReadLine();
    if (line == null)
    {
	break;
    }
    Console.WriteLine(line); // Use line.
}

List

List

It is possible to put an entire file into a collection. One common requirement for programs is that you need to read in a file line-by-line. You can store all those lines in a generic List or ArrayList. We next use a List in this way.

List

It creates a List. In the above code, a new List generic object that stores strings is created. The example shows the using keyword. The using keyword surrounds the StreamReader. This ensures correct disposal of resources.

While keyword

Then:It runs a while-loop. This loop reads in lines until the end of the file.

And:ReadLine returns null at the end of a file. There is no need to check for EOF. Finally it adds lines to the List.

While
Program that reads all lines: C#

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
	//
	// Read in a file line-by-line, and store it all in a List.
	//
	List<string> list = new List<string>();
	using (StreamReader reader = new StreamReader("file.txt"))
	{
	    string line;
	    while ((line = reader.ReadLine()) != null)
	    {
		list.Add(line); // Add to list.
		Console.WriteLine(line); // Write to console.
	    }
	}
    }
}

Output

First line of your file.txt file.
Second line.
Third line.
Last line.

Close

Program

This is an error-prone way of using StreamReader. We open a file in one line, deal with the file in another few lines, and then make a call to close the file. The code shown below is cumbersome and unclear.

There are several problems with this style of code. It is harder to type and read, and bugs could creep into the code. Other than those problems, it works well. If the file is not there, it will throw an exception.

Also:If the exception is thrown, you must have a finally block to release the unmanaged resources.

Finally
Program that uses Dispose: C#

using System;
using System.IO;

class Program
{
    static void Main()
    {
	//
	// Read a line from a file the old way.
	//
	StreamReader reader = new StreamReader("file.txt");
	string line = reader.ReadLine();
	reader.Close();
	// You should call Dispose on "reader" here, too.
	reader.Dispose();
	Console.WriteLine(line);
    }
}

Output

First line of file.txt file.

StreamWriter

ABC: letters

The StreamWriter,
as you might guess,
writes files. It can be used in programs that use StreamReader, but the two types are independent and can be used by themselves. These are the easiest ways to process text files.

StreamWriter

Summary

C# programming language

We used the StreamReader class to read in lines of text files. The using keyword has performance that is essentially equal to any manual ways. The base class library's file IO methods are efficient. They are well-designed.

And:The "using" pattern reduces the resources used. It makes programs more reliable.


C#: File