This article describes, how to read a text file in C# language with stream Reader class.
- StreamReader class implements TextReader class that read sequential series of characters from byte stream in a particular encoding.
I have added a Values.txt file in my Visual Studio project through right click the project and add new item as shown below
Now the following code will show , how we can read this text file through stream reader class.
staticvoid Main(string args)
StreamReader myReader = newStreamReader("Values.txt");
string line = "";
while (line != null)
line = myReader.ReadLine();
if (line != null)
In the above code,
- In the above code, we first reference IO, TEXT and different other libraries by keyword using like using System.IO etc
- Then we created a stream reader object and pass the input file name as its parameter.
- ReadLine() is a method of StreamReader class that read the line of character from current stream and returns the data as string.
- While(line!=null) here we use line!=null condition in while loop to break the loop when there is null in line.
- Close() method closes the streamReader object and the underlying streams and releases any system resources that are associated with the reader.
This is how we read a text file with stream Reader class. Below is the output of this code.Best WordPress Themes and Plugins with Great Team and Support!