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 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 fileHello 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).
Detail 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).
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.