File.ReadAllLines
Learn to read lines as an array with File.ReadAllLines.
Reading lines with File.ReadAllLines
The File.ReadAllLines method reads a text file line by line and returns a string[] array. Each line is one element; line endings are stripped. Call: string[] lines = File.ReadAllLines("list.txt");.
This is ideal for line-oriented data: task lists, config files, logs. You can walk the lines with foreach. lines.Length gives the line count. Empty lines are included in the array.
Walking the lines
The result of ReadAllLines is an array, so you can walk it with foreach or index it with for. lines[0] gives the first line. Arrays are zero-based.
To get the line count, use lines.Length. If you add System.Linq you can also use lines.Count(), lines.First(), lines.Where(...). You can also pass the path as a variable: File.ReadAllLines(path).
Exercise Write and read lines
First create a three-line file with File.WriteAllLines("list.txt", new[] { "Apple", "Pear", "Cherry" });. Then read it with File.ReadAllLines and print each line with Console.WriteLine in a foreach loop.
Show example solution
First write with File.WriteAllLines("list.txt", new[] { "Apple", "Pear", "Cherry" });, then read with var lines = File.ReadAllLines("list.txt");, finally foreach (var line in lines) Console.WriteLine(line);.
Example solution:
using System;
using System.IO;
class Program
{
static void Main()
{
File.WriteAllLines("list.txt", new[] { "Apple", "Pear", "Cherry" });
var lines = File.ReadAllLines("list.txt");
foreach (var line in lines)
{
Console.WriteLine(line);
}
}
}
Test yourself
-
Match each method to its output
- ReadAllText
- string
- ReadAllLines
- string[]
- WriteAllText
- void
- Exists
- bool
-
Complete the ReadAllLines call
string[] lines = File.____("list.txt");Show answer
string[] lines = File.ReadAllLines("list.txt"); -
What does ReadAllLines return?
File.ReadAllLines("a.txt")- string[]
- string
- List<string>
- char[]
Show answer
string[] — Correct. ReadAllLines returns string[]; each line is one element.