Read in a file in C# with StreamReader

CsharpProgrammingServer Side Programming

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
raja
Published on 04-Sep-2018 08:07:17
Advertisements