StreamReader: StreamReader handles text files. We read a text file in C# by Using StreamReader. This will correctly dispose of system resources and make code simpler. Implements a TextReader that reads characters from a byte stream in a particular encoding.
StreamReader Usage:
- Open file with constructor
- read string with read/readline methods
- close
The following examples require to add namespace using System.IO;
Usage 1:
1 2 3 4 5 6 7 8 9 10 11 |
StreamReader sr = new StreamReader("sample.txt"); string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } sr.Close(); |
Usage 2: The using statement ensures that method StreamReader.Dispose is called.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Program { static void Main(string[] args) { FileStream file = new FileStream(@"C:\sample.txt", FileMode.Open, FileAccess.Read); using (var sr = new StreamReader(file, Encoding.UTF8)) { while (sr.Peek() >= 0) { Console.WriteLine(sr.ReadLine()); } } Console.ReadLine(); } } |