

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- How to read a text file with C++?
- How to read a .txt file with RandomAccessFile in Java?
- How to read a text file in Selenium with python?
- Read integers from a text file with C++ ifstream
- How to read a Pandas CSV file with no header?
- How to read a text file in Python?
- How to open a file in read and write mode with Python?
- Python - Read csv file with Pandas without header?
- How to read a single file inside a zip archive with PHP
- How to open a binary file in read and write mode with Python?
- Change a file attribute to read only in Java
- How can we read a JSON file in Java?
- How to read a file into a string in Golang?
- How to read a txt file in external storage with runtime permission in android?
- Read last line from file in PHP
Advertisements