How to Read a Text File
Reading a text file is a common task. The File.ReadAllLines() method is a simple way to read every line of a file into a string array. For larger files, consider using File.ReadLines() which returns an IEnumerable<string> and reads the file line-by-line, improving memory efficiency.
C# Example Code
using System;
using System.IO;
public class FileReader
{
public static void Main(string[] args)
{
string filePath = "example.txt";
// Ensure the file exists before reading
File.WriteAllText(filePath, "Hello World!\nThis is a test file.");
try
{
string[] lines = File.ReadAllLines(filePath);
Console.WriteLine("File content:");
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
catch (IOException e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}