StreamReader Class in C# with Example

StreamReader Class in C# with Example
Rating: 5 - 1 Votes

StreamReader Class in C# with Example

StreamReader Class in C# with Example

StreamReader Class in C# with Example

StreamReader class is basically used for reading text files.  StreamReader class resides in System.IO namespace.  If you want to make use of StreamReader class, then you must include System.IO namespace by making use of using keyword on top of your code.  StreamReader class got various methods like ReadLine(), ReadToEnd(), etc.

Upon creating an instance of StreamReader class, you can directly pass path of text file to the constructor, which you want to read.  Since the path of file contains some special characters like backslash(\), we make use of escape sequence by adding another backslash in front of it or you can use @ symbol in front of it to make the path verbatim literal.  Please click here for tutorial about Escape Sequence and Verbatim Literal in C#.

There is a method called Close() in the StreamReader class. You must invoke that method after you finished reading your text file to release any system resources associated with the reader.

Output:

Hi,

This tutorial is written by Fwait.com.  Keep browsing for more tutorials on this
site.

Thank You!

Press any key to continue . . .

This is another code example where you can read the text file line by line using StreamReader Class.

 Output:

Hi,

This tutorial is written by Fwait.com.  Keep browsing for more tutorials on this
site.

Thank You!
Press any key to continue . . .