The File class provides two static methods to read a text file in C#. The File.ReadAllText() method opens a text file, reads all the text in the file into a string, and then closes the file.
The following code reads a text file into a string.
// Read entire text file content in one string
string text = File.ReadAllText(textFile);
Console.WriteLine(text);
The File.ReadAllLines() method opens a text file, reads all lines of the file into a string array, and then closes the file. The following code snippet reads a text file into an array of strings.
// Read a text file line by line.
string[] lines = File.ReadAllLines(textFile);
foreach (string line in lines)
Console.WriteLine(line);
One more way to read a text file is using a StreamReader class that implements a TextReader and reads characters from a byte stream in a particular encoding. The ReadLine method of StreamReader reads one line at a time.
// Read file using StreamReader. Reads file line by line
using(StreamReader file = new StreamReader(textFile)) {
int counter = 0;
string ln;
while ((ln = file.ReadLine()) != null) {
Console.WriteLine(ln);
counter++;
}
file.Close();
Console.WriteLine($ "File has {counter} lines.");
}
The complete code sample uses the above-discussed methods to read a text file and display its content to the console. To test this code, find a text file (or create one with some text in it) on your machine and change the "textFile" variable to the full path of your .txt file.
using System;
using System.IO;
namespace ReadATextFile {
class Program {
// Default folder
static readonly string rootFolder = @ "C:\Temp\Data\";
//Default file. MAKE SURE TO CHANGE THIS LOCATION AND FILE PATH TO YOUR FILE
static readonly string textFile = @ "C:\Temp\Data\Authors.txt";
static void Main(string[] args) {
if (File.Exists(textFile)) {
// Read entire text file content in one string
string text = File.ReadAllText(textFile);
Console.WriteLine(text);
}
if (File.Exists(textFile)) {
// Read a text file line by line.
string[] lines = File.ReadAllLines(textFile);
foreach(string line in lines)
Console.WriteLine(line);
}
if (File.Exists(textFile)) {
// Read file using StreamReader. Reads file line by line
using(StreamReader file = new StreamReader(textFile)) {
int counter = 0;
string ln;
while ((ln = file.ReadLine()) != null) {
Console.WriteLine(ln);
counter++;
}
file.Close();
Console.WriteLine($ "File has {counter} lines.");
}
}
Console.ReadKey();
}
}
}
Summary
The code example in this article taught you how to use the File class to read a text file in C#.
Here is a detailed article on the File class in C#: Working With File Class In C# (c-sharpcorner.com)