HomeSearch

C# StreamReader ReadLine, ReadLineAsync Examples

Use the StreamReader ReadLine method and the List. Get a List from a file.

ReadLine, ReadLineAsync.

ReadLine is a StreamReader method. It returns the next text line from the file. We can process each line separately as it is encountered.StreamReader

With ReadLineAsync,

we can read lines in an asynchronous method—one that returns immediately, before the file is read. We can do other processing while the file is read.

An example.

To start, ReadLine works well with the List collection. We have to first create a List, and then we add the "using" statement to begin our usage of the StreamReader.List

Using: For StreamReader, we use the using keyword to read the lines. This provides automatic disposal, releasing important resources.

Using

String: We store the ReadLine result in a string local. This will be null if we are done reading the file.

List: We call Add on the instance of List here. This appends another string to the List.

List Add

Finally: We display the results to the console with Console.WriteLine. You will see all the lines in the file displayed here.

Console.WriteLine
C# program that uses ReadLine and List using System; using System.Collections.Generic; using System.IO; class Program { static void Main() { // Change this to point to a real file. const string fileName = @"C:\programs\file.txt"; // Create new List. List<string> lines = new List<string>(); // Use using-keyword for disposing. using (StreamReader reader = new StreamReader(fileName)) { // Use while not null pattern in while loop. string line; while ((line = reader.ReadLine()) != null) { // Insert logic here. // ... The "line" variable is a line in the file. // ... Add it to our List. lines.Add(line); } } // Print out all the lines in the list. foreach (string value in lines) { Console.WriteLine(value); } } } Contents,[file.txt]: Hello my friend Welcome to the Internet Third line in file Output Hello my friend Welcome to the Internet Third line in file

ReadLineAsync.

We can use ReadLineAsync in a method that is marked as async. This means the method can execute while other code is still executing (after it is called, before it returns).

So: The async method is non-blocking. We can still process each line in the file as we encounter it.

Tip: Async code can be a huge benefit when the file is slow to be read, and other processing must occur.

Important: We must use the await and async keywords, and the Task class for any return values (if needed).

async, awaitStreamReader ReadToEndAsync
C# program that uses ReadLineAsync using System; using System.IO; using System.Threading.Tasks; class Program { const string _file = @"C:\programs\huge-file"; public static void Main() { // For testing. CreateHugeFile(); // We can run code in Main() without stopping for all the ReadLine calls in CountLinesAsync. Console.WriteLine("In main method (1)"); Task<int> task = CountLinesAsync(); // This next statement is reached immediately, before the file is read. Console.WriteLine("In main method (2)"); task.Wait(); Console.WriteLine("Result (3): " + task.Result); } static void CreateHugeFile() { using (StreamWriter writer = new StreamWriter(_file)) { for (int i = 0; i < 10000; i++) { writer.WriteLine("Huge file line"); } } } static async Task<int> CountLinesAsync() { int count = 0; using (StreamReader reader = new StreamReader(_file)) { while (true) { string line = await reader.ReadLineAsync(); if (line == null) { break; } count++; } } Console.WriteLine("At end of CountLinesAsync"); return count; } } Output In main method (1) In main method (2) At end of CountLinesAsync Result (3): 10000

IOException.

You will want to catch IOException if your application's stability is critical. You could catch all IO exceptions and return an empty array if the file cannot be read.IOExceptionCatch

A discussion.

This code gives you a chance to test each line, as with a regular expression, before adding it. You could use File.ReadAllLines, but you can't test each line first that way.Regex

Arrays: When you have added all the correct lines to the List, you can convert the List to an array, as with ToArray().

Convert List, ArrayToArray

Note: If you need a complete array of lines from a file, you can use the static File.ReadAllLines method.

File.ReadAllLines

A summary.

We read each line into a file line-by-line. This can provide superior memory management over allocating an entire array. We can test each line before storing it.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.