In this chapter you will learn:
- What is StreamReader Class?
- How to read file using StreamReader Class?
- Programming Examples and Code
What is StreamReader Class?
StreamReader
class allows you to read text files easily. Its implementation is easy and it is widely popular among the programmer. However, there are dozens of way to read text file in C# file handling but StreamReader
Class is more popular in list.
StreamReader
Class
- Implements a
TextReader
that reads characters from a byte stream in a particular encoding. StreamReader
class uses UTF-8 Encoding by defaults.StreamReader
class is designed for character input in a particular encoding.- Use this class for reading standard text file.
- By default, it is not thread safe.
How to read file using StreamReader class?
As mentioned above it is very easy to read text file using StreamReader Class. Here I am going to write a program that does following thing:- Write some data on text file using StreamWriter class and
- Read those data using StreamReader class.
Programming Examples and Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace StreamReader_Class { class Program { static void Main(string[] args) { string file = @"D:\csharpfile.txt"; //Writer data to text file using (StreamWriter writer = new StreamWriter(file)) { writer.WriteLine("This tutorial explains how to use StreamReader Class in C# Programming"); writer.WriteLine("Good Luck!"); } //Reading text file using StreamReader Class using (StreamReader reader = new StreamReader(file)) { Console.WriteLine(reader.ReadToEnd()); } Console.ReadKey(); } } }
Output:
This tutorial explains how to use StreamReader Class in C# Programming
Good Luck! _
Summary
In this chapter you learned StreamReader
class with complete programming example. In the next chapter you will learn TextWriter Class in C#.