C# StreamReader ReadLine, ReadLineAsync ExamplesUse the StreamReader ReadLine method and the List. Get a List from a file.
dot net perls

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.



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.


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


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. We see all the lines in the file.


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); } } }

Hello my friend Welcome to the Internet Third line in file
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).


StreamReader 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; } }
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.



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.


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, Array


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


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.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.