To read text files, use StreamReader class in C#.
Add the name of the file you want to read −
StreamReader sr = new StreamReader("hello.txt");Use the ReadLine() method and get the content of the file in a string −
using (StreamReader sr = new StreamReader("hello.txt")) {
str = sr.ReadLine();
}
Console.WriteLine(str);Let us see the following code −
Example
using System.IO;
using System;
public class Program {
public static void Main() {
string str;
using (StreamWriter sw = new StreamWriter("hello.txt")) {
sw.WriteLine("Hello");
sw.WriteLine("World");
}
using (StreamReader sr = new StreamReader("hello.txt")) {
str = sr.ReadLine();
}
Console.WriteLine(str);
}
}It creates the file “hello.text” and adds text to it. After that, using StreamReader class it reads the first line of your file −
Output
The following is the output.
Hello