C#Dot Net Perls

C#
Using StreamReader Examples

by Sam Allen

Problem

Read in a file from the disk and manage the file resources properly. Utilize using StreamReader to read in the file. We want a simple and graceful way to use StreamReader and dispose of our resources. This will also help with other expensive objects like database connections and commands and graphics objects.

C# Solution

In many languages, you must open a file in one line, deal with the file in another few lines, and then make a call to close to the file. You can do this in C#, too. The code shown below is the unclear version, which we can replace with using.

// Read a line from a file the old way.
StreamReader sr = new StreamReader("file.txt");
string line = sr.ReadLine();
sr.Close();
// You ought to call Dispose on 'sr' here, too, but often that is omitted.

What's wrong with it?

It is cumbersome to type and read, and bugs could creep into the code. It works as intended: we just open a file, read a line out of it, and then close it. (Note that if the file is not there, it will throw an exception, which you should probably be on the lookout for.)

using keyword

The using statement in C# allows you to leave the file disposal and opening routines to the C# compiler's knowledge of scope. This statement will instruct .NET to do all the dirty cleanup work with your file. Let's look at the same example I showed above, but with this new syntax.

// This is ideal. .NET will deal with memory in its optimal way.
// Plus, it is fewer characters to type. My recommendation: Always
// use using unless you are in an unusual circumstance.
string line;
using (StreamReader sr = new StreamReader("file.txt"))
{
    line = sr.ReadLine();
}

Scope is important here

When objects go out of scope, some code is called to clean them up. The garbage collector is run and your program's memory is reclaimed. (A scope in your C# code is a block between brackets.) Object goes out of scope when the block it was declared in is finished. Scope allows the compiler to make many assumptions about your program.

Read all lines in a file

Here's another example of "using StreamReader". One very common requirement for programs is that you need to read in a file line-by-line. And you want to store all those lines in a generic List or ArrayList object in C#. Let's look at an example that reads in a file line-by-line and stores it in a List.

// Read in a file line-by-line, and store it all in a List.
// You can then use the List to look at the contents of the
// file without having to open the file again.
List<string> allLines = new List<string>();
using (StreamReader reader = new StreamReader("file.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // "line" is a line in the file. Add it to our List.
        allLines.Add(line);
    }
}

Conclusion

The using keyword has performance that is essentially equal to any manual ways of doing it. Overall, I feel that .NET file IO methods are very efficient and well-designed. Using can reduce the resources used by your program--both your own personal resources, and those of the environment and electrical outlet.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge