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 snippet reads a text file in to a 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.
-
- 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.
-
- 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 {
-
- static readonly string rootFolder = @ "C:\Temp\Data\";
-
- static readonly string textFile = @ "C:\Temp\Data\Authors.txt";
-
- static void Main(string[] args) {
- if (File.Exists(textFile)) {
-
- string text = File.ReadAllText(textFile);
- Console.WriteLine(text);
- }
-
- if (File.Exists(textFile)) {
-
- string[] lines = File.ReadAllLines(textFile);
- foreach(string line in lines)
- Console.WriteLine(line);
- }
-
- if (File.Exists(textFile)) {
-
- 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();
- }
- }
- }