StreamReader
This C# class
reads text files. It is found in the System.IO
namespace. StreamReader
is a fast and efficient way to handle text files in this language.
StreamReader
is often used with the using
-statement, a language construct that helps dispose of system resources. We often place a loop inside "using."
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 System; using System.IO; // ... The StreamReader will free resources on its own. string line; using (StreamReader reader = new StreamReader("file.txt")) { line = reader.ReadLine(); } Console.WriteLine(line);First line of your file.txt file.
Next, we see an alternate syntax form for the inner-loop in the StreamReader
. It uses an if
-statement with a break
in it.
using System; using System.IO; using (StreamReader reader = new StreamReader("C:\\programs\\file.txt")) { while (true) { string line = reader.ReadLine(); if (line == null) { break; } Console.WriteLine(line); // Use line. } }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
. This List
generic collection can store strings.while
-loop. This loop reads in lines until the end of the file.ReadLine
returns null
at the end of a file. There is no need to check for EOF. Finally it adds lines to the List
.using System; using System.Collections.Generic; using System.IO; // // 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. } }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.
using System; using System.IO; // ... 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);First line of file.txt file.
StreamReader
easily reads in lines of text files. The using
-keyword has good performance. The base class library's file IO methods are efficient. They are well-designed.