Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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
Advertisements
