Reading a text file in C# requires the System.IO
class. There are two main methods for reading a text file:
ReadAllText()
ReadAllLines()
ReadAllText()
methodThe 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.
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); } }
ReadAllLines()
methodThe 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.
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); } } }
RELATED TAGS
View all Courses