HomeSearch

C# StreamReader Example

Read text files with StreamReader inside a using-statement. Use ReadLine and while-loops.

StreamReader.

This reads text files. It is found in the System.IO namespace. It provides good performance and is easy to add to programs.

Using statement.

StreamReader is often used with the using-statement. This construct helps dispose of the system resources. We often place a loop inside "using."

First example.

We 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.

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

Using

Info: A scope is a block between brackets. When objects go out of scope, the garbage collector or finalization code is run.

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

C# program that uses StreamReader using System; using System.IO; class Program { static void Main() { // ... The StreamReader 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.

While loop.

Next, we see an alternate syntax form for the inner-loop in the StreamReader. It uses an if-statement with a break in it.IfBreak
C# program that uses while-true loop using System; using System.IO; class Program { static void Main() { using (StreamReader reader = new StreamReader("C:\\programs\\file.txt")) { while (true) { string line = reader.ReadLine(); if (line == null) { break; } Console.WriteLine(line); // Use line. } } } } Output 123 Bird Hello friend

List.

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

New: The program creates a List. This List generic collection can store strings.

While: 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
C# program that reads all lines 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.

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

Warning: There are problems with this style of code. It is harder to type and read, and bugs could creep into the code.

However: Other than those problems, it works well. If the file is not there, it will throw an exception.

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

Finally
C# program that uses Dispose 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(); // ... We should call Dispose on "reader" here, too. reader.Dispose(); Console.WriteLine(line); } } Output First line of file.txt file.

Async, await.

A StreamReader can be used with the async and await keywords. The ReadLineAsync method is called with "await." This allows other code to execute while a file is read.async, awaitReadLineAsync

ReadToEnd.

To read the entire file into a string at once, please use the ReadToEnd method on StreamReader. This eliminates a loop in your program.StreamReader ReadToEnd

Async: For situations where you have excess CPU usage during file loads, try using the Async method for a speedup. A benchmark is provided.

StreamReader ReadToEndAsync

File locations.

It is sometimes helpful to create a folder in a location like "C:\examples\." Then you can specify this absolute path (which is easy to examine) in your programs.Path

StreamWriter.

This writes files. It can be used in programs that use StreamReader, but the two types are independent and can be used by themselves.StreamWriter

A summary.

StreamReader easily reads inlines of text files. The using-keyword has good performance. The base class library's file IO methods are efficient. They are well-designed.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.