C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Using: For StreamReader, we use the "using" keyword to read the lines. This provides automatic disposal, releasing important resources.
UsingString: 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 AddFinally: We display the results to the console with Console.WriteLine. We see all the lines in the file.
ConsoleC# 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
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).
asyncStreamReader ReadToEndAsyncC# 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
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, ArrayToArrayNote: If you need a complete array of lines from a file, you can use the static File.ReadAllLines method.
File.ReadAllLines