Hell Friends, In C# if we have to deal with Stream of content we have to use StreamReader class present in System.IO namespace. In this article I will show you how we can use StreamReader with Example.
StreamReader Example in C#
This class can be used to read the contents from the stream, such as file. The general syntax for using the class is as below:
StreamReader sr = new StreamReader("LocationAndNameOfFile");
One example of the class is shown below:
{ StreamReader myReader = new StreamReader(new FileStream("project.json", FileMode.Open, FileAccess.Read)); string line = " "; while(line != null) { line = myReader.ReadLine(); if(line != null) { Console.WriteLine(line); } } myReader.Dispose(); }
In the above code we will read one by one all the lines of the file. This can be useful of we don’t know file size and file is getting updated continuously by some other source.
The other counter part of ReadLine is ReadToEnd. This method read all the contents of the file in one go. This can be used in case where we are sure of the size of the file. Below is an example.
static void Main(string[] args) { StreamReader myReader = new StreamReader(new FileStream("project.json", FileMode.Open, FileAccess.Read)); Console.WriteLine(myReader.ReadToEnd()); myReader.Dispose(); }
I hope this article can help you to use this class in better way.
Leave a Reply