How to read a text file in C#

Reading a text file in C# requires the System.IO class. There are two main methods for reading a text file:

  • ReadAllText()
  • ReadAllLines()

The ReadAllText() method

The ReadAllText() method takes the path of the file to be read and the encoding of the file (optional). Take a look at the code below to see how this method can be used to read a file.

main.cs
data.txt
using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
var path = "data.txt";
string content = File.ReadAllText(path, Encoding.UTF8);
Console.WriteLine(content);
}
}

The ReadAllLines() method

The ReadAllLines() method takes the path of the file to be read and the encoding of the file(optional). The method reads a text file into an array of strings where each line in the file is one element in the array. Take a look at the code below to see how ReadAllLines can be used.

main.cs
data.txt
using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
var path = "data.txt";
string[] lines = File.ReadAllLines(path, Encoding.UTF8);
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved