Read in a file in C# with StreamReader



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

 Live Demo

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
Updated on: 2020-04-03T10:43:20+05:30

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements